Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么~pd.isnull()返回-2?_Python - Fatal编程技术网

Python 为什么~pd.isnull()返回-2?

Python 为什么~pd.isnull()返回-2?,python,Python,我在做一些处理缺失值的快速测试时遇到了这种奇怪的行为。当查看~pd.isnull(np.nan)时,我希望它返回False,但它返回-2。这是为什么?这是因为您使用了算术、位求反运算符而不是逻辑求反。您的混淆是有道理的,因为标量的这个奇怪结果与“反转”逻辑数组时看到的结果不一致: >>> pd.isnull([np.nan]) array([ True]) >>> ~pd.isnull([np.nan]) array([False]) 这里有一些奇怪的事情在

我在做一些处理缺失值的快速测试时遇到了这种奇怪的行为。当查看
~pd.isnull(np.nan)
时,我希望它返回False,但它返回-2。这是为什么?

这是因为您使用了算术、位求反运算符而不是逻辑求反。

您的混淆是有道理的,因为标量的这个奇怪结果与“反转”逻辑数组时看到的结果不一致:

>>> pd.isnull([np.nan])
array([ True])
>>> ~pd.isnull([np.nan])
array([False])
这里有一些奇怪的事情在起作用。请注意:

>>> pd.isnull(np.nan)
True
所以,把numpy和熊猫排除在外,你基本上是在问为什么:

>>> ~True
-2
这是因为
bool
int
的子类:

>>> issubclass(bool, int)
True
>>> True == 1
True
>>> int.__invert__(True)
-2
表达式
~x
钩住数据模型。现在,
bool
没有实现
\uuuuu invert\uuuu
,因此它返回到第一个实现的超类,即
int

>>> issubclass(bool, int)
True
>>> True == 1
True
>>> int.__invert__(True)
-2
因为,
~x
本质上是计算
-(x+1)
。政府实际上是这样定义的


不幸的是,
bool
要以更合理的方式覆盖
\uuuu invert\uuuu
,即
~b
返回与
非b
相同的结果,同时仍然保持bool是int的向后兼容性保证,这并不容易。您最终会遇到一个麻烦的特殊情况,
x==y
但是
~x!=~y

如果您仔细分析您测试的数据类型,您的测试将更有价值。啊,现在这非常有意义,谢谢。将您的答案与@CiaPan的答案结合起来,就如何编写更好的测试进行了讨论。