Reut
Reut

Reputation: 1592

Change values in one dataframe if values appear in another dataframe based on one column value

I have two dataframe, "big" and "correction":

big:

>>>ID    class    fruit
0  1     medium   banana
1  2     medium   banana
2  3     high     peach
3  4     low      nuts
4  5     low      banana

and correction:

>>> ID  class  time  fruit
0   2  medium   17   melon
1   5  high     19   oranges

I want to fix the table "big" according to information in table correction. in order to get the following table:

>>>ID    class    fruit
0  1     medium   banana
1  2     medium   **melon**
2  3     high     peach
3  4     low      nuts
4  5     **high** **oranges**

as you can see, the starred values "fixed" according to the correction tabl, on the ID field.

I thought to use for nested loop but I believe there are better ways to get the same results.

Upvotes: 3

Views: 73

Answers (2)

anky
anky

Reputation: 75080

Try df.update after aligning the indexes of both dataframes:

big.set_index("ID",inplace=True)
big.update(correction.set_index("ID")

big = big.reset_index() #ifyou want `ID` as a column back
print(big)

   ID   class    fruit
0   1  medium   banana
1   2  medium    melon
2   3    high    peach
3   4     low     nuts
4   5    high  oranges

Upvotes: 3

Scott Boston
Scott Boston

Reputation: 153460

Let's try:

corr_df.set_index('ID').combine_first(big_df.set_index('ID'))

Upvotes: 1

Related Questions