Python numpy questions: Why does np.all not evaluate to True when given a 2D numpy array populated with NaN (not a number)?

huangapple go评论62阅读模式
英文:

Python numpy questions: Why does np.all not evaluate to True when given a 2D numpy array populated with NaN (not a number)?

问题

我一直在使用 Python 中的 np.all 进行实验。我已经查看了这里的文档:
https://numpy.org/doc/stable/reference/generated/numpy.all.html

我期望下面的 np.all 语句评估为:[True, True, True] 和 True,但它们没有。

我在这里漏掉了什么?

我尝试了以下代码:

import numpy as np

NA = float("NAN")
arrNA = np.array([[NA, NA, NA], [NA, NA, NA], [NA, NA, NA]])

print(np.all(arrNA == NA, axis=0)) 
#这会打印出[False, False, False],但np.array中的每个元素都等于NA。为什么不是True?

print(np.all(arr == NA)) 
#这也打印出false,但np.array中的每个元素都是NA。为什么不是True?
英文:

I've been experimenting with np.all in Python. I've looked at the documentation here:
https://numpy.org/doc/stable/reference/generated/numpy.all.html

I'm expecting the np.all statements below to evaluate to: [True, True, True] and True but they don't.

What am I missing here?

I've tried the code below:

import numpy as np

NA = float("NAN")
arrNA = np.array([[NA, NA, NA], [NA, NA, NA], [NA, NA, NA]])

print(np.all(arrNA == NA, axis=0)) 
#This prints [False, False, False], but every element in the np.array is equal to NA. Why not True?

print(np.all(arr == NA)) 
#This also prints false, but every element in the np.array is NA. Why not True?

</details>


# 答案1
**得分**: 1

根据IEEE浮点标准,NaN不等于自身:
```python
>>> np.nan == np.nan
False

因此,当您写arrNA == NA时,您会得到一个布尔数组,其中每个元素都是False

如果您想检查NaN值的存在,您可以使用np.isnan

>>> np.all(np.isnan(arrNA))
True
英文:

According to the IEEE floating point standard, NaN is not equal to itself:

&gt;&gt;&gt; np.nan == np.nan
False

So when you write arrNA == NA, you get a boolean array where every element is False.

If you want to check for the presence of NaN values, you can use np.isnan:

&gt;&gt;&gt; np.all(np.isnan(arrNA))
True

huangapple
  • 本文由 发表于 2023年2月19日 05:02:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定