Pandas将一帧中的值指定给选定行中另一帧中的相应列

2024-05-18 06:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

DF1
|col1 |  col2 |  col3 |
  12     v1      v12
  3      v3      v13
  5      v5      v14
  7      v10     v15

DF2
|col2| col3|
  x1  y2
  x2  y1

output DF1
|col1 |  col2 |  col3 |
  12     x2      y1
  3      v3      v13
  5      v5      v14
  7      x1     y2

我想将行7,12 inDF1设置为DF2的值,而不显式指定列

类似于DF1[7,12]=DF2的东西


Tags: v3col2col3col1df1v1df2x1
2条回答

您需要使用update

df2.index=[0,3]# change the index you want to update in df1, then just using update 
df1.update(df2)
df1
Out[404]: 
   col1 col2 col3
0    12   x1   y2
1     3   v3  v13
2     5   v5  v14
3     7   x2   y1

仅使用.loc语句:

DF1.loc[DF1.col1.isin([12,7]), 'col2'] = DF2.col2.values

返回:

>>> DF1
   col1 col2 col3
0    12   x1  v12
1     3   v3  v13
2     5   v5  v14
3     7   x2  v15

相关问题 更多 >