覆盖不同大小的 pandas 的DataFrames中的列 [英] Overwrite columns in DataFrames of different sizes pandas

查看:67
本文介绍了覆盖不同大小的 pandas 的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的值.所需的数据帧是这样的:

And I want to update the values of df1 with the ones on df2 whenever there is a match in the ids. The desired dataframe is this one:

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

如何从以上两个数据框中获取该数据?

How can I get that from the above two dataframes?

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

I have tried using merge, but fewer records and it keeps both columns:

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中的值优先级

You can use set_index and combine first to give precedence to values in 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

这篇关于覆盖不同大小的 pandas 的DataFrames中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆