mm_
mm_

Reputation: 1735

Why does numpy.isin() behaves different when passed numpy.nan as a value?

I want to check if a set of values are in a numpy array. While doing this I found np.isin() behaves differently if the value passed is np.nan. That is:

import numpy as np

a = np.array([2, np.nan])

print(np.isin(2, a))
print(np.isin(np.nan, a))

output:

True
False

I have two questions:

How do I check if np.nan is in an array?

Why does these two values behave differently when passed to np.isin() ?

Upvotes: 1

Views: 230

Answers (1)

wim
wim

Reputation: 362507

The rough equivalent is

 any([x == np.nan for x in a.flat])

Which will fail because nan is not even equal with itself. This oddity is not specific to numpy:

>>> float('nan') in [float('nan')]
False

How do I check if np.nan is in an array?

Use np.isnan(a).any() instead.

Upvotes: 1

Related Questions