numpy NaN 并不总是被识别 [英] numpy NaN not always recognized

查看:89
本文介绍了numpy NaN 并不总是被识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我很困惑:

```
a=np.array([1,2,np.nan,3])    # an array with a nan
print(np.isnan(a)[2])         # it truly is a nan
print(a[2])                   # it quacks like a nan
print(np.nan is np.nan)       # nan's can be compared
print(a[2] is np.nan)         # But then, this isn't a nan after all!!??

>>> True
>>> nan
>>> True
>>> False
```

我知道我们不允许将 nan 与 == 进行比较,但是应该允许与 is 进行比较?毕竟在将 nan 与自身进行比较时它有效吗?

I know we're not allowed to compare nan's with ==, but with is should be allowed? After all it works when comparing nan to itself?

感谢您对这里发生的事情的任何提示.

Thanks for any hints to what is going on here.

推荐答案

这与其说是关于 Python is 运算符的问题,不如说是关于对元素进行索引或拆箱的问题数组确实:

This isn't so much a question about the Python is operator, as about what indexing, or unboxing, an element of an array does:

In [363]: a=np.array([1,2,np.nan,3])
In [364]: a[2]
Out[364]: nan
In [365]: type(a[2])
Out[365]: numpy.float64
In [366]: a[2] is a[2]
Out[366]: False

a[2] 不只是返回 nan.它返回一个 np.float64 对象,其值为 np.nan.另一个 a[2] 将产生另一个 np.float64 对象.两个这样的对象在 is 意义上不匹配.对于任何数组元素都是如此,而不仅仅是 nan 值.

a[2] doesn't simply return nan. It returns a np.float64 object whose values is np.nan. Another a[2] will produce another np.float64 object. Two such objects don't match in the is sense. That's true for any array element, not just nan values.

由于 == 不适用于 nan,我们只能使用 np.isnan 函数.

Since == doesn't work for nan, we are stuck with using the np.isnan function.

np.nan 是唯一的 float 对象(在此会话中),但 a[2] 未设置为该对象.

np.nan is a unique float object (in this session), but a[2] is not set to that object.

如果数组被定义为对象类型:

If the array was defined as an object type:

In [376]: b=np.array([1,2,np.nan,3], object)
In [377]: b[2] is np.nan
Out[377]: True

这里的 is 是 True - 因为 b 包含指向内存中已经存在的对象的指针,包括 np.nan 对象.对于这样构造的列表也是如此.

here the is is True - because b contains pointers to objects that already exist in memory, including the np.nan object. Same would be true for a list constructed like that.

这篇关于numpy NaN 并不总是被识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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