Reputation: 602
Is it possible to fill a column according to other conditions?
I made a false algorithm:
if (df.b == 3) & (df.c == 0) & (df.a == None):
df['d'] == 0
else:
df['b']
and I tried
import pandas
df = pandas.DataFrame([{'a': None, 'b': 3, 'c': 0},
{'a': "string", 'b': 0, 'c': 3},
{'a': "string", 'b': 3, 'c': 0}])
df['d'] = [0 if ((df.b == 3) & (df.c == 0) & (df.a == None)) else pass]
SyntaxError: invalid syntax
I need
df = pandas.DataFrame([{'a': None, 'b': 3, 'c': 0, 'd': 0},
{'a': "string", 'b': 0, 'c': 3, 'd': 0},
{'a': "string", 'b': 3, 'c': 0, 'd': 3}])
Upvotes: 0
Views: 66
Reputation: 49
df['d'] = df['b'].mask(df['b'].eq(3) & df['c'].eq(0) & df['a'].isnull(), 0)
print (df) a b c d 0 None 3 0 0 1 string 0 3 0 2 string 3 0 3
Upvotes: 1
Reputation: 30930
IIUC, Series.mask
df['d'] = df['b'].mask(df['b'].eq(3) & df['c'].eq(0) & df['a'].isnull(), 0)
print (df)
a b c d
0 None 3 0 0
1 string 0 3 0
2 string 3 0 3
Upvotes: 2