问题描述
据我了解,==
检查值的相等性,而is
检查值背后的结构的身份(例如,其他语言中的===
).
As far as I understand it, ==
checks for equality of value, and is
checks for identity of structure behind value (as, say ===
in some other languages).
鉴于此,我不理解以下内容:
Given that, I don't understand the following:
np.isnan(30) == False
Out[19]:
True
np.isnan(30) is False
Out[20]:
False
其他身份检查似乎并非如此:
It appears not to be the case with other identity checks:
(5 == 4) == False
Out[22]:
True
(5 == 4) is False
Out[23]:
True
似乎np.isnan()
返回False
作为值而不是作为标识.为什么会这样呢?
It appears as if np.isnan()
returns False
as a value, but not as identity. Why is that the case?
推荐答案
numpy.isnan()
返回兼容类型的对象:
>>> import numpy
>>> type(numpy.isnan(0))
<class 'numpy.bool_'>
这是一个自定义布尔值,可以有效地存储在numpy数组中,请参见 Numpy的数据类型文档. numpy.isnan()
函数还可以对数组进行操作,从而生成另一个结果数组:
This is a custom boolean that can be stored efficiently in numpy arrays, see Numpy's Data Types documentation. The numpy.isnan()
function can also operate on arrays, producing another array with results:
>>> numpy.isnan(numpy.array([1, 2]))
array([False, False], dtype=bool)
其中dtype
还是Numpy布尔对象.
where again the dtype
is the Numpy boolean object.
Python不能保证布尔操作必须始终返回单例布尔值.无论如何,您绝不应该测试is True
或is False
.直接在布尔运算中使用numpy.isnan()
输出,使用not
测试错误值:
Python makes no guarantees that boolean operations must always return a singleton boolean value. You should never test for is True
or is False
anyway. Use numpy.isnan()
output directly in boolean operations, use not
to test for false values:
if numpy.isnan(foo):
和
if not numpy.isnan(bar):
这篇关于np.isnan()== False,但是np.isnan()不是False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!