英文:
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:
>>> 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
:
>>> np.all(np.isnan(arrNA))
True
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论