在构建Pandas DataFrame中使用逻辑运算符 [英] Using logical operators in building a Pandas DataFrame
问题描述
我有两段熊猫代码片段,我认为它们应该是等效的,但是第二段代码并没有达到我的期望.
I have two snippets of pandas code which I think should be equivalent, but the second one doesn't do what I expect.
# 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]))]
每个部分(例如all_data['Source'] == 2
)单独执行我期望的操作,但是由于最终结果与列表理解版本的结果不同,因此我似乎对逻辑运算符做错了事. /p>
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.
推荐答案
&
运算符的绑定比==
(或任何比较运算符)更紧密.请参见文档.一个简单的例子是:
The &
operator binds more tightly than ==
(or any comparison operator). See the documentation. A simpler example is:
>>> 2 == 2 & 3 == 3
False
这是因为它被分组为2 == (2 & 3) == 3
,然后调用了比较链.这就是您的情况.您需要在每个比较之间加上括号.
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.
这篇关于在构建Pandas DataFrame中使用逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!