带有"== True"的表达式和“是真实的";给出不同的结果 [英] Expressions with "== True" and "is True" give different results

查看:63
本文介绍了带有"== True"的表达式和“是真实的";给出不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 MCVE :

#!/usr/bin/env python3                                           

import pandas as pd

df = pd.DataFrame([True, False, True])

print("Whole DataFrame:")
print(df)

print("\nFiltered DataFrame:")
print(df[df[0] == True])

我期望的输出如下:

Whole DataFrame:
     0
  0  True
  1  False
  2  True

Filtered DataFrame:
     0
  0  True
  2  True

好的,但是 PEP8 样式似乎是错误的,它说: E712与True的比较应为if cond is Trueif cond .所以我将其更改为is True而不是== True,但现在失败了,输出为:

Okay, but the PEP8 style seems to be wrong, it says: E712 comparison to True should be if cond is True or if cond. So I changed it to is True instead of == True but now it fails, the output is:

Whole DataFrame:
    0
0   True
1  False
2   True

Filtered DataFrame:
0     True
1    False
2     True
Name: 0, dtype: bool

这是怎么回事?

推荐答案

这里的问题是,在df[df[0] == True]中,您没有将对象与True 进行比较.

The catch here is that in df[df[0] == True], you are not comparing objects to True.

正如其他答案所说,==pandas中重载以生成Series而不是通常的bool. []也被重载,以解释Series并给出过滤后的结果.该代码本质上等效于:

As the other answers say, == is overloaded in pandas to produce a Series instead of a bool as it normally does. [] is overloaded, too, to interpret the Series and give the filtered result. The code is essentially equivalent to:

series = df[0].__eq__(True)
df.__getitem__(series)

因此,您不会在此处留下==来违反PEP8.

So, you're not violating PEP8 by leaving == here.

本质上,pandas提供了熟悉的语法不同寻常的语义-这就是造成混乱的原因.

Essentially, pandas gives familiar syntax unusual semantics - that is what caused the confusion.

根据Stroustroup (sec.3.3.3),操作员重载已引起麻烦自从它发明以来就一直对此保持关注(他不得不认真考虑是否将其包含在C ++中). 在C ++中看到了更多滥用情况,戈斯林在Java中遇到了另一种极端情况,禁止完全如此,事实证明那是一个极端.

Accoring to Stroustroup (sec.3.3.3), operator overloading has been causing trouble due to this ever since its invention (and he had to think hard whether to include it into C++). Seeing even more abuse of it in C++, Gosling ran to the other extreme in Java, banning it completely, and that proved to be exactly that, an extreme.

结论是,现代语言和代码趋向于具有运算符重载,但要密切注意不要过度使用它,并使语义保持一致.

As a conclusion, modern languages and code tend to have operator overloading but watch closely not to overuse it and for semantics to stay consistent.

这篇关于带有"== True"的表达式和“是真实的";给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆