Why does assert np.nan == np.nan throw an error?

If a

assert 1 == 1

      

ok, why:

assert np.nan == np.nan

      

causes an assertion error?

Even more confusing, this is normal:

assert np.nan != np.nan

      

What's the best way to check for nan

?

+3


source to share


2 answers


NaN

has the property that it is not equal to itself, you should use np.isnan

to test the values NaN

here np.isnan(np.nan)

will give True

:

In[5]:
np.nan == np.nan

Out[5]: False

In[6]:
np.nan != np.nan

Out[6]: True

In[7]:
np.isnan(np.nan)

Out[7]: True

      



As noted by Lukasz Rogalski, the is

following will also work:

In [10]: np.nan is np.nan

Out[10]: True

      

+8


source


Use math.isnan(value)

. NaN does not compare to itself because it indicates failure and may not have been produced in the same way. I'm not sure why it is isnan

missing from the documentation, but it is present in both CPython 3.4 and 2.7.



+1


source







All Articles