我有两个这样的数据框:
df1 = pd.DataFrame({'ID1':['A','B','C','D','E','F'],
'ID2':['0','10','80','0','0','0']})
df2 = pd.DataFrame({'ID1':['A','D','E','F'],
'ID2':['50','30','90','50'],
'aa':['1','2','3','4']})
我想插入ID2
在df2
进入ID2
在df1
,同时插入aa
进入df1
根据ID1
获取像这样的新数据框:
df_result = pd.DataFrame({'ID1':['A','B','C','D','E','F'],
'ID2':['50','10','80','30','90','50'],
'aa':['1','NaN','NaN','2','3','4']})
我尝试过使用合并,但没有成功。
最佳答案
您可以使用combine_first
将索引设置为 ID1 后在 DataFrame 上:
(df2.set_index('ID1') # values of df2 have priority in case of overlap
.combine_first(df1.set_index('ID1')) # add missing values from df1
.reset_index() # reset ID1 as column
)
输出:
ID1 ID2 aa
0 A 50 1
1 B 10 NaN
2 C 80 NaN
3 D 30 2
4 E 90 3
5 F 50 4
关于python - 将值从一个数据帧插入/替换/合并到另一个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70958734/