Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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.

like image 459
Reut Avatar asked Feb 01 '26 03:02

Reut


2 Answers

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
like image 70
anky Avatar answered Feb 02 '26 15:02

anky


Let's try:

corr_df.set_index('ID').combine_first(big_df.set_index('ID'))
like image 22
Scott Boston Avatar answered Feb 02 '26 16:02

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!