Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Update Conditional on DF2 Column Values

Tags:

python

pandas

I have 2 dataframes:

df1

       hair    eyes   gender  

joe     br      bl      m
mary    bl      br      f
pete    rd      gr      m

and I want to update df1 with values from df2 IF subject to some values in some additional columns

       hair    eyes   gender  weight  height

joe     bk      gr      m       150     72
mary    bl      br      f       125     55
pete    rd      gr      m       180     68

I want to do this:

df1.update(df2)   #if df2 height is over 70

but not sure how or if it's possible to specify condition.

The output I'd get after the operation is:

       hair    eyes   gender  

joe     bk      gr      m
mary    bl      br      f
pete    rd      gr      m

So only Joe was updated because his height was over 70.

Is there some way to conditionally specify update or is it best to just make another df where df2['height'] > 70?

Thanks in advance

like image 302
Windstorm1981 Avatar asked Nov 24 '25 08:11

Windstorm1981


1 Answers

Just filter df2 before you update:

df1.update(df2[df2['height'] > 70])
like image 154
jpp Avatar answered Nov 26 '25 21:11

jpp



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!