I am aware that AND corresponds to &
and NOT, ~
. What is the element-wise logical OR operator? I know "or" itself is not what I am looking for.

- 10,268
- 18
- 50
- 51

- 4,646
- 7
- 43
- 72
3 Answers
The corresponding operator is |
:
df[(df < 3) | (df == 5)]
would elementwise check if value is less than 3 or equal to 5.
If you need a function to do this, we have np.logical_or
. For two conditions, you can use
df[np.logical_or(df<3, df==5)]
Or, for multiple conditions use the logical_or.reduce
,
df[np.logical_or.reduce([df<3, df==5])]
Since the conditions are specified as individual arguments, parentheses grouping is not needed.
More information on logical operations with pandas can be found here.

- 379,657
- 97
- 704
- 746

- 7,094
- 3
- 30
- 44
-
43The round brackets *are* important – Gerard Aug 08 '16 at 15:22
-
5`|` and `np.logical_or` behave differently in the presence of NaNs. See https://stackoverflow.com/q/37131462/2596586 – Frank Nov 14 '19 at 00:18
-
Just a comment: `or` is not working here. Only `|` works. – Alan Mar 15 '20 at 00:17
To take the element-wise logical OR of two Series a
and b
just do
a | b

- 2,708
- 2
- 26
- 32
If you operate on the columns of a single dataframe, eval
and query
are options where or
works element-wise. You don't need to worry about parenthesis either because comparison operators have higher precedence than boolean/bitwise operators. For example, the following query
call returns rows where column A values are >1 and column B values are > 2.
df = pd.DataFrame({'A': [1,2,0], 'B': [0,1,2]})
df.query('A > 1 or B > 2') # == df[(df['A']>1) | (df['B']>2)]
# A B
# 1 2 1
or with eval
you can return a boolean Series (again or
works just fine as element-wise operator).
df.eval('A > 1 or B > 2')
# 0 False
# 1 True
# 2 False
# dtype: bool

- 10,268
- 18
- 50
- 51