user6873419
user6873419

Reputation:

Update pandas dataframe from another dataframe

I have two dataframes.

df1 is

     name     colour    count
0    apple    red       3
1    orange   orange    2
3    kiwi     green     12

df2 is

     name    count
0    kiwi   2
1    apple  1

I want to update df1 with count from df2 based on name match. Expected result:

     name     colour    count
0    apple    red       1
1    orange   orange    2
3    kiwi     green     2

I am using this but the results are incorrect.

df3 = df2.combine_first(df1).reindex(df1.index)

How can I do this correctly?

Upvotes: 0

Views: 35

Answers (1)

jezrael
jezrael

Reputation: 862406

Create index by name in both DataFrames for matching by them by DataFrame.set_index, then DataFrame.combine_first and last DataFrame.reset_index for column from index:

df = df2.set_index('name').combine_first(df1.set_index('name')).reset_index()
print (df)
     name  colour  count
0   apple     red    1.0
1    kiwi   green    2.0
2  orange  orange    2.0

Upvotes: 2

Related Questions