99

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.

cottontail
  • 10,268
  • 18
  • 50
  • 51
Keith
  • 4,646
  • 7
  • 43
  • 72

3 Answers3

154

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
deinonychusaur
  • 7,094
  • 3
  • 30
  • 44
12

To take the element-wise logical OR of two Series a and b just do

a | b
Jonathan Stray
  • 2,708
  • 2
  • 26
  • 32
0

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
cottontail
  • 10,268
  • 18
  • 50
  • 51