Reputation: 2657
Using assign
in Pandas 1.0 I would like to create a new flag column based on the following logic:
import numpy as np
import pandas as pd
df = pd.DataFrame({'val': [10, 2, 0, 1, 0.4, 2]})
df = df.assign(
flag=lambda x: False if np.bool(x['val'] == 0) else True if np.bool(x['val'] < 0.5) else False
)
I expect:
df
val flag
0 10 False
1 2 False
2 0 False
3 1 False
4 0.4 True
5 2 False
Instead I get:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
I tried with np.where(), np.any(), np.all() but I do not get the expected result.
Upvotes: 1
Views: 152
Reputation: 863751
Chain condition by &
for bitwise AND:
df = pd.DataFrame({'val': [10, 2, 0, 1, 0.4, 2]})
df = df.assign(flag= (df['val'] < 0.5) & (df['val'] != 0))
If val
is count by some chained method is necessary lambda:
df = df.assign(flag=lambda x: (x['val'] < 0.5) & (x['val'] != 0))
print (df)
val flag
0 10.0 False
1 2.0 False
2 0.0 False
3 1.0 False
4 0.4 True
5 2.0 False
Upvotes: 2