简体   繁体   English

根据另一个 dataframe 中匹配的 id 替换 dataframe 列值

[英]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.

相关问题 根据在另一个 dataframe 中匹配/包含特定列的值过滤 dataframe - Filter a dataframe based on values matching/containing in particular column in another dataframe 根据另一个 dataframe 的匹配行和列填充 dataframe 中的值 - Populate values in a dataframe based on matching row and column of another dataframe 用来自另一个数据框的匹配ID替换熊猫中的单元格值 - Replace Cell Values in Pandas with matching ID from another dataframe 根据另一列的值替换Pandas数据框的Column的值 - Replace values of a Pandas dataframe's Column based on values of another column 根据另一个 dataframe 替换 dataframe 值 - replace dataframe values based on another dataframe 根据条件从另一个 dataframe 值替换列的值 - Python - Replace values of a column from another dataframe values based on a condition - Python 基于匹配来自另一个数据帧pandas的值的新列 - New column based on matching values from another dataframe pandas Pyspark 基于另一个 dataframe 替换数组列上的值 - Pyspark replace values on array column based on another dataframe Pandas数据框:根据另一列中的值替换多行 - Pandas dataframe: Replace multiple rows based on values in another column 基于另一个数据框 python pandas 替换列值 - 更好的方法? - Replace column values based on another dataframe python pandas - better way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM