Python Pandas 中的元素逻辑 OR

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24775648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:10:43  来源:igfitidea点击:

Element-wise logical OR in Pandas

pythonpandasboolean-logiclogical-operatorsboolean-operations

提问by Keith

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

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

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

我知道 AND 对应于&和 NOT, ~。但是OR呢?

采纳答案by deinonychusaur

The corresponding operator is |:

对应的运算符是|

 df[(df < 3) | (df == 5)]

would elementwise check if value is less than 3 or equal to 5.

将元素检查值是否小于 3 或等于 5。



If you need a function to do this, we have np.logical_or. For two conditions, you can use

如果您需要一个函数来执行此操作,我们有np.logical_or. 对于两种情况,您可以使用

df[np.logical_or(df<3, df==5)]

Or, for multiple conditions use the logical_or.reduce,

或者,对于多个条件,请使用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.

可以在此处找到有关 Pandas 逻辑运算的更多信息。

回答by Jonathan Stray

To take the element-wise logical OR of two Series aand bjust do

取两个系列的逐元素逻辑或,a然后b执行

a | b