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

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

问题描述

当将 NumPy Not-a-Number 值转换为布尔值时,它变为 True,例如如下.

<预><代码>>>>将 numpy 导入为 np>>>布尔(np.nan)真的

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

(我怀疑在 Octave 中可能会发生同样的行为.)

解决方案

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

在[1]中:bool(float('nan'))输出[1]:真

这些规则在文档中有详细说明.

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

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.)

解决方案

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.

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天全站免登陆