Jimmy
Jimmy

Reputation: 137

Logical Operation On a Few Columns Pandas

I am trying to create a column in Pandas that looks to see whether any of the columns in the selected set of columns have a False value in them.

Index Item 1 Truth Item 1 Value Item 2 Truth Item 2 Value
First True 65 True 10
Second False 50 True 55

There are a lot more than 2 of the "Truth" columns so list comprehension etc. would be very helpful here. The output for Row 1 should be True and the output for Row 2 should be false. I have so far tried using .apply and all() etc. but nothing seems to be working so far.

Thanks!

Upvotes: 1

Views: 34

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195653

You can .filter the dataframe and the use .all() with axis=1 (rows):

df["result"] = df.filter(regex=r"Truth$").all(axis=1)
print(df)

Prints:

    Index  Item 1 Truth  Item 1 Value  Item 2 Truth  Item 2 Value  result
0   First          True            65          True            10    True
1  Second         False            50          True            55   False

Upvotes: 2

Related Questions