Reputation: 19496
If
assert 1 == 1
is fine, then why does:
assert np.nan == np.nan
cause an assertion error?
What's even more confusing, this is OK:
assert np.nan != np.nan
What's the best way to test for nan
?
Upvotes: 18
Views: 9506
Reputation: 394389
NaN
has the property that it doesn't equal itself, you should use np.isnan
to test NaN
values, here np.isnan(np.nan)
will yield 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
Upvotes: 26
Reputation: 15887
Use np.isnan(value)
. NaN doesn't compare equal to itself because it indicates a failure, and might not have been produced the same way. I'm not sure why isnan
is missing in the CPython documentation, but it's present in math
for both CPython 3.4 and 2.7, and as a ufunc in numpy
.
Upvotes: 3