![](/img/trans.png)
[英]Filter a dataframe based on values matching/containing in particular column in another dataframe
[英]Replace dataframe column values based on matching id in another dataframe
我正在嘗試根據不同的 dataframe 中的值替換 dataframe 中的值。請假設兩個數據框中都有其他列。 一個簡單的例子:
df1
id name ......
123 city a
456 city b
789 city c
789 city c
456 city b
123 city a
等等等等
df2
id name ......
123 City A
456 City B
789 City C
所以得到的 df 應該是:
id name ......
123 City A
456 City B
789 City C
789 City C
456 City B
123 City A
我在 pandas 中嘗試了一些合並選項,但沒有成功。 有沒有一種簡單的方法可以根據id
上的匹配將第一個 dataframe 中的所有值替換為第二個 dataframe 中的值?
任何幫助表示贊賞
你可以做
df1['New name']=df1.id.map(df2.set_index('id').name)
更新
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')
要么
df1=df1.set_index('id')
df1.update(df2.set_index('id'))
df1.reset_index(inplace=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.