Replace Value in based on conditions in other columns

Viewed 24

I would like to change the value (c,d) where there is a duplicate name (a) AND condition = 'Cancel' (b)

enter image description here

import pandas as pd

data1 = {'a' : ['Mary','Mary','John','Jenny','Jenny'],
         'b' : ['Approve','Cancel','Approve','Approve','Cancel'],
         'c' : [100,200,300,400,500],
         'd' : [200,200,300,400,500]
        }

df1= pd.DataFrame(data1)
df1

I can select the specific rows using df1[(df1.duplicated(['a'], keep=False) & (df1['b']=='Cancel'))] but struggle to find a way to change values....I am researching np.where and df.apply

Thanks in advance.

1 Answers

Use 'loc' with the column names that you want to change:

df1.loc[(df1.duplicated(['a'], keep=False) & (df1['b']=='Cancel')),
        ['c','d']] = 0

Output:

       a        b    c    d
0   Mary  Approve  100  200
1   Mary   Cancel    0    0
2   John  Approve  300  300
3  Jenny  Approve  400  400
4  Jenny   Cancel    0    0
Related