Skip to main content
 首页 » 编程设计

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

2025年05月04日9yxwkf

据我所知,== 检查值是否相等,而 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 True 或is False 无论如何。在 boolean 运算中直接使用numpy.isnan() 输出,使用not 来测试假值:

if numpy.isnan(foo): 

和

if not numpy.isnan(bar):