Reputation: 1194
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. A simple example:
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
id name ......
123 City A
456 City B
789 City C
So the resulting df should be:
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. 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
?
Any help is appreciated
Upvotes: 2
Views: 3083
Reputation: 323276
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)
Upvotes: 3