How do I create a new df.column based on 2+ conditions in Pandas without iteration?
I have a normal df
A = pd.DataFrame([[1, 5, 2], [2, 4, 4], [3, 3, 1], [4, 2, 2], [5, 1, 4]],
columns=['A', 'B', 'C'], index=[1, 2, 3, 4, 5])
If I want to create a column based on a condition in another column, I will do something like this and it works as expected.
In [5]: A['D'] = A['C'] > 2
In [6]: A
Out[6]:
A B C D
1 1 5 2 False
2 2 4 4 True
3 3 3 1 False
4 4 2 2 False
5 5 1 4 True
However, if I want to do the same using 2 conditions ... for example:
A['D'] = A['C'] > 2 and A['B'] > 2 or A['D'] = A['C'] > 2 & A['B'] > 2
I get infamous
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
How can I solve without iteration? The purpose of creating this new column based on two conditions is to use a groupby function of type:
A.groupby('D').apply(custom_fuction)
So, maybe there is a way to use groupby to accomplish all of this, but I don't know how.
thank
+3
source to share
1 answer
Use &
, not and
for performing elementary logical operations and operations:
In [40]: A['D'] = (A['C'] > 2) & (A['B'] > 2)
In [41]: A
Out[41]:
A B C D
1 1 5 2 False
2 2 4 4 True
3 3 3 1 False
4 4 2 2 False
5 5 1 4 False
You can also omit the column definition D
:
In [42]: A.groupby((A['C'] > 2) & (A['B'] > 2))
Out[42]: <pandas.core.groupby.DataFrameGroupBy object at 0xab5b6ac>
+1
source to share