Using logical operators in building a Pandas DataFrame

房东的猫 提交于 2019-11-29 12:15:42

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.

 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.

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!