I want to join but only in cases where a certain other condition is True
I have a DataFrame df1 that looks like this
ID Bool Val
1111 True AAA
2222 False BBB
3333 True CCC
4444 False DDD
I then have another DataFrame df2 like this
ID Val
1111 EEE
3333 FFF
5555 GGG
And I want to overwrite the Val column in df1 where the ID match and the Bool is True. This would look like this
ID Bool Val
1111 True EEE
2222 False BBB
3333 True FFF
4444 False DDD
As you can see the AAA and CCC have been overwritten.
I am thinking of doing this with an if statement
You can use boolean indexing with loc to select the rows of df1 where 'bool' column is True ,also use pandas.Series.map to assign correctly:
b=df1['Bool']
df1.loc[b,'Val']=df1.loc[b,'ID'].map(df2.set_index('ID')['Val'])
print(df1)
ID Bool Val
0 1111 True EEE
1 2222 False BBB
2 3333 True FFF
3 4444 False DDD
Also you can use pandas.Series.replace:
df1.loc[b,'Val']=df1.loc[b,'ID'].replace(df2.set_index('ID')['Val'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With