gpt4 book ai didi

python - np.isnan() == False,但 np.isnan() 不是 False

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:56 26 4
gpt4 key购买 nike

据我所知,== 检查值是否相等,而 is 检查值背后结构的同一性(比如 == = 在某些其他语言中)。

鉴于此,我不明白以下内容:

np.isnan(30) == False
Out[19]:
True
np.isnan(30) is False
Out[20]:
False

其他身份检查似乎并非如此:

(5 == 4) == False
Out[22]:
True
(5 == 4) is False
Out[23]:
True

它看起来好像 np.isnan() 返回 False 作为值,而不是身份。为什么会这样?

最佳答案

numpy.isnan() 返回一个兼容类型的对象:

>>> import numpy
>>> type(numpy.isnan(0))
<class 'numpy.bool_'>

这是一个自定义 boolean 值,可以有效地存储在 numpy 数组中,参见 Numpy's Data Types documentation . numpy.isnan() 函数也可以对数组进行操作,生成另一个包含结果的数组:

>>> numpy.isnan(numpy.array([1, 2]))
array([False, False], dtype=bool)

dtype 又是 Numpy boolean 对象。

Python 不保证 boolean 运算必须始终返回单例 boolean 值。你永远不应该测试is Trueis False 无论如何。在 boolean 运算中直接使用numpy.isnan() 输出,使用not 来测试假值:

if numpy.isnan(foo):

if not numpy.isnan(bar):

关于python - np.isnan() == False,但 np.isnan() 不是 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42277260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com