[英]Replace dataframe column values based on matching id in another dataframe
I'm trying to replace values in a dataframe based on values in a different dataframe. Please assume there are other columns in both dataframes.我正在尝试根据不同的 dataframe 中的值替换 dataframe 中的值。请假设两个数据框中都有其他列。 A simple example:
一个简单的例子:
df1 df1
id name ......
123 city a
456 city b
789 city c
789 city c
456 city b
123 city a
so on and so forth等等等等
df2 df2
id name ......
123 City A
456 City B
789 City C
So the resulting df should be:所以得到的 df 应该是:
id name ......
123 City A
456 City B
789 City C
789 City C
456 City B
123 City A
I tried out with a few merge options in pandas with no luck.我在 pandas 中尝试了一些合并选项,但没有成功。 Is there an easy way to replace all the values in the first dataframe with the values from the second dataframe based on a match on
id
?有没有一种简单的方法可以根据
id
上的匹配将第一个 dataframe 中的所有值替换为第二个 dataframe 中的值?
Any help is appreciated任何帮助表示赞赏
You can do你可以做
df1['New name']=df1.id.map(df2.set_index('id').name)
Update更新
namediff=df1.columns.difference(df2.columns).tolist()+['id']
df3=df2.drop(df2.columns.difference(df1.columns),axis=1)
df1=df1[namediff].merge(df3,on='id')
Or要么
df1=df1.set_index('id')
df1.update(df2.set_index('id'))
df1.reset_index(inplace=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.