Following the title of the question, the case is this:
Creating dataframe:
import pandas as pd
df = pd.DataFrame({ 'a': ['one', 'one', 'three', 'two', 'eleven', 'two'],
'b': [45, 34, 556, 32, 97, 33],
'c': [234, 66, 12, 44, 99, 3],
'd': [123, 45, 55, 98, 17, 22] })
df
Output:
a b c d
0 one 45 234 123
1 one 34 66 45
2 three 556 12 55
3 two 32 44 98
4 eleven97 99 17
5 two 33 3 22
Let's say I want to add a column 'e' which is the sum of the columns 'b', 'c' and 'd'. It's simple:
df['e'] = df.b + df.c + df.d
df
Output:
a b c d e
0 one 45 234 123 402
1 one 34 66 45 145
2 three 556 12 55 623
3 two 32 44 98 174
4 eleven 97 99 17 213
5 two 33 3 22 58
Now I want one more column 'f' , but based on the following condition:
if df.a == 'one' and df.b < 50:
df['f'] = 0
elif df.a == 'two' and df.d > 50:
df['f'] = 1
else:
df['f'] = 2
But of course this code does not work.
out:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(),
a.item(), a.any() or a.all().
How could those condition be correctly implemented?