I have a data frame, where i want to replace the values in column 'A' as NULL when values in column 'B' is either 'X' or 'Y'. For any other values in column 'B' (i.e., 'Z' or 'M') i want to retain the existing values in column 'A'
A | B |
---|---|
aaa | X |
bbb | Y |
ccc | X |
ddd | Y |
eee | Z |
fff | M |
This is the expected result
A | B |
---|---|
NULL | X |
NULL | Y |
NULL | X |
NULL | Y |
eee | Z |
fff | M |
This is what i have tried so far;
def func(colB):
if colB in ['X' , 'Y']:
return 'NULL'
df['A'] = df['B'].map(func)
This replaces the values in column A as NULL when B = ['x','y'] and returns blank when it is any other value. I want to retain the values if it does not match.
CodePudding user response:
This can be done using where()
and isin()
df['A'] = df['A'].where(~df['B'].isin(['X','Y']),'NULL')
Output:
A B
0 NULL X
1 NULL Y
2 NULL X
3 NULL Y
4 eee Z
5 fff M