Skip to content Skip to sidebar Skip to footer

Change Value Of One Dataframe By Value From Other Dataframe Pandas

i have a dataframe df1 id value 1 100 2 100 3 100 4 100 5 100 i have another dataframe df2 id value 2 50 5 30 i want to replace th

Solution 1:

Use combine_first, but first set_index by id in both DataFrames:

Notice: id column in df2 has to be unique.

df = df2.set_index('id').combine_first(df1.set_index('id')).reset_index()
print (df)
   id  value
0   1  100.0
1   2   50.0
2   3  100.0
3   4  100.0
4   5   30.0

Solution 2:

A loc based solution -

i = df1.set_index('id')
j = df2.set_index('id')

i.loc[j.index, 'value'] =  j['value']
df2 = i.reset_index()
df2

   id  value
0   1    100
1   2     50
2   3    100
3   4    100
4   5     30

Post a Comment for "Change Value Of One Dataframe By Value From Other Dataframe Pandas"