Element-wise logical OR in Pandas

PythonPandasBoolean LogicLogical OperatorsBoolean Operations

Python Problem Overview


I would like the element-wise logical OR operator. I know "or" itself is not what I am looking for.

I am aware that AND corresponds to & and NOT, ~. But what about OR?

[1]: https://stackoverflow.com/questions/21415661/logic-operator-for-boolean-indexing-in-pandas "here" [2]: https://stackoverflow.com/questions/15998188/how-can-i-obtain-the-element-wise-logical-not-of-a-pandas-series

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

a | b

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKeithView Question on Stackoverflow
Solution 1 - PythondeinonychusaurView Answer on Stackoverflow
Solution 2 - PythonJonathan StrayView Answer on Stackoverflow