Element-wise logical OR in Pandas

Question:

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.

Asked By: Keith

||

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.

Answered By: deinonychusaur

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

a | b
Answered By: Jonathan Stray

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
Answered By: cottontail