使用逻辑运算符构建 Pandas DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19581582/
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-09-13 21:16:32  来源:igfitidea点击:

Using logical operators in building a Pandas DataFrame

pythonpandaslogical-operators

提问by Jamie Bull

I have two snippets of pandas code which I think should be equivalent, but the second one doesn't do what I expect.

我有两个 Pandas 代码片段,我认为它们应该是等效的,但是第二个片段没有达到我的预期。

# snippet 1
    data = all_data[[((np.isfinite(all_data[self.design_metric][i]) 
                    and all_data['Source'][i] == 2)) 
                    or ((np.isfinite(all_data[self.actual_metric][i]) 
                    and all_data['Source'][i] != 2))
                    for i in range(len(all_data))]]


# snippet 2
    data = all_data[(all_data['Source'] == 2 &
                    np.isfinite(all_data[self.design_metric])) |
                    (all_data['Source'] != 2 &
                    np.isfinite(all_data[self.actual_metric]))]

Each section (e.g. all_data['Source'] == 2) does what I expect on its own but it seems that I'm doing something wrong with the logical operators as the final result is coming out with a different result to the list comprehension version.

每个部分(例如all_data['Source'] == 2)都按照我自己的期望执行,但似乎我在逻辑运算符上做错了,因为最终结果与列表理解版本的结果不同。

回答by BrenBarn

The &operator binds more tightly than ==(or any comparison operator). See the documentation. A simpler example is:

&操作者比结合更紧密地==(或任何比较操作符)。请参阅文档。一个更简单的例子是:

>>> 2 == 2 & 3 == 3
False

This is because it is grouped as 2 == (2 & 3) == 3, and then comparison chaining is invoked. This is what is happening in your case. You need to put parentheses around each comparison.

这是因为它被分组为2 == (2 & 3) == 3,然后调用比较链。这就是你的情况。您需要在每个比较周围加上括号。

 data = all_data[((all_data['Source'] == 2) &
                np.isfinite(all_data[self.design_metric])) |
                ((all_data['Source'] != 2) &
                np.isfinite(all_data[self.actual_metric]))]

Note the extra parentheses around the ==and !=comparisons.

请注意==!=比较周围的额外括号。

回答by alko

Along with priority, there is a difference between AND and & operators, first one being boolean and the latter being binary bitwise. Also, you must be aware of boolead expressions.

除了优先级之外,AND 和 & 运算符之间也存在差异,第一个是布尔值,后者是按位二进制。此外,您必须了解 boolead 表达式。

See examples in the following snippet:

请参阅以下代码段中的示例:

logical expressions

逻辑表达式

>>> 1 and 2
1

>>> '1' and '2'
'1'

>>> 0 == 1 and 2 == 0 or 0
0

bitwise operators

按位运算符

>>> 1 & 2
0

>>> '1' & '2'
Traceback (most recent call last):
  ...
TypeError: unsupported operand type(s) for &: 'str' and 'str'

>>> 0 == 1 & 2 == 0 | 0
True