Taylrl
Taylrl

Reputation: 3919

Join based only on condition python

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

Upvotes: 3

Views: 227

Answers (1)

ansev
ansev

Reputation: 30920

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'])

Upvotes: 5

Related Questions