Pandas Data Frame – logical or of all columns
Question:
I have a dynamically created data frame which contains, multiple columns with True/False values. Let’s say that it looks like this:
A
B
C
True
True
False
False
True
False
False
False
False
I need to create a column which values will be a result of logical or on the rest of the columns.
The output would look like this:
A
B
C
OR
True
True
False
True
False
True
False
True
False
False
False
False
Answers:
Use DataFrame.any
:
df['OR'] = df.any(axis=1)
If need filter only some columns:
cols = ['A','B']
df['OR'] = df[cols].any(axis=1)
I have a dynamically created data frame which contains, multiple columns with True/False values. Let’s say that it looks like this:
A | B | C |
---|---|---|
True | True | False |
False | True | False |
False | False | False |
I need to create a column which values will be a result of logical or on the rest of the columns.
The output would look like this:
A | B | C | OR |
---|---|---|---|
True | True | False | True |
False | True | False | True |
False | False | False | False |
Use DataFrame.any
:
df['OR'] = df.any(axis=1)
If need filter only some columns:
cols = ['A','B']
df['OR'] = df[cols].any(axis=1)