覆盖不同大小的熊猫的DataFrames中的列


问题内容

我有以下两个数据框:

df1 = pd.DataFrame({'ids':[1,2,3,4,5],'cost':[0,0,1,1,0]})
df2 = pd.DataFrame({'ids':[1,5],'cost':[1,4]})

而且我想在ID匹配时用df2上的值更新df1的值。所需的数据帧是这样的:

df_result = pd.DataFrame({'ids':[1,2,3,4,5],'cost':[1,0,1,1,4]})

我如何从上面两个数据框中得到它?

我尝试使用合并,但是记录较少,并且保留了两列:

results = pd.merge(df1,df2,on='ids')
results.to_dict()
{'cost_x': {0: 0, 1: 0}, 'cost_y': {0: 1, 1: 4}, 'ids': {0: 1, 1: 5}}

问题答案:

您可以使用set_index并首先合并以赋予df2中的值优先级

df_result = df2.set_index('ids').combine_first(df1.set_index('ids'))
df_result.reset_index()

你得到

   ids  cost
0   1   1
1   2   0
2   3   1
3   4   1
4   5   4