Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas conditional filter

Tags:

python

pandas

I have a dataframe

   A     B     C
0  True  True  True
1  True  False False
2  False False False

I would like to add a row D with the following conditions:

D is true, if A, B and C are true. Else, D is false.

I tried

df['D'] = df.loc[(df['A'] == True) & df['B'] == True & df['C'] == True] 

I get

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

Then I tried to follow this example and wrote a similar function as suggested in the link:

def all_true(row):

   if row['A'] == True:
      if row['B'] == True:
         if row['C'] == True:
             val = True
   else:
      val = 0

return val

df['D'] = df.apply(all_true(df), axis=1)

In which case I get

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I'd appreciate suggestions. Thanks!

like image 417
Meeep Avatar asked Dec 17 '22 19:12

Meeep


1 Answers

Or even better:

df['D']=df.all(1)

And now:

print(df)

Is:

       A      B      C      D
0   True   True   True   True
1   True  False  False  False
2  False  False  False  False
like image 140
U12-Forward Avatar answered Feb 16 '23 10:02

U12-Forward