熊猫中的元素逻辑或

我想要元素逻辑 OR 操作符。我知道“或”本身不是我要找的。

我知道 AND 对应于 &而不是 ~,但 OR 呢?

128543 次浏览

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.

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

a | b