Reputation: 462
I'am having some trouble when initializing a numpy array with numpy.NAN as below.
>>> import numpy
>>> a = numpy.zeros(2)
>>> a
array([ 0., 0.])
>>> a[:] = numpy.NAN
>>> a
array([ nan, nan])
>>> a[0] is numpy.NAN
False
Why is that? I have tried to initilize a single variable with NAN and get var is numpy.NAN as True. What happends when NAN is assign to an array?
And another question is when some of the elements in the arrary is NAN, how can I distinguish them from others? Thanks a lot!
Upvotes: 1
Views: 1926
Reputation: 280465
It's a NaN. It's just that is
doesn't work the way you think it does with NumPy arrays. When you assign
a[:] = numpy.NAN
NumPy doesn't actually fill a
with references to the numpy.NAN
object. Instead, it fills the array with doubles with NaN values at C level.
When you then access an array element with a[0]
, NumPy has no record of the original object used to initialize that cell. It just has the numeric value. It has to construct a new Python object to wrap that value, and the new wrapper is not the same object as numpy.NAN
. Thus, the is
check returns False
.
Note that generally, comparing numbers with is
is a bad idea anyway. Usually, what you want is ==
, to compare their numeric values. However, ==
also returns False
for NaNs, so what you need is numpy.isnan
:
>>> numpy.isnan(a[0])
True
>>> numpy.isnan(a)
array([ True, True], dtype=bool)
Upvotes: 9