为什么“不是数字"?在Python/Numpy中转换为布尔值时,值是否等于True? [英] Why do "Not a Number" values equal True when cast as boolean in Python/Numpy?

查看:200
本文介绍了为什么“不是数字"?在Python/Numpy中转换为布尔值时,值是否等于True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将NumPy非数字值转换为布尔值时,它变为True,例如如下.

When casting a NumPy Not-a-Number value as a boolean, it becomes True, e.g. as follows.

>>> import numpy as np
>>> bool(np.nan)
True

这与我的直觉期望完全相反.这种行为是否有合理的原则?

This is the exact opposite to what I would intuitively expect. Is there a sound principle underlying this behaviour?

(我怀疑八度音阶中可能会出现相同的行为.)

(I suspect there might be as the same behaviour seems to occur in Octave.)

推荐答案

这绝不是NumPy特有的,但与Python处理NaN的方式是一致的:

This is in no way NumPy-specific, but is consistent with how Python treats NaNs:

In [1]: bool(float('nan'))
Out[1]: True

文档中阐明了规则.

The rules are spelled out in the documentation.

我认为可以合理地认为NaN的真值应为False.但是,这不是该语言目前的工作方式.

I think it could be reasonably argued that the truth value of NaN should be False. However, this is not how the language works right now.

这篇关于为什么“不是数字"?在Python/Numpy中转换为布尔值时,值是否等于True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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