zabop
zabop

Reputation: 7852

Comparing NumPy arrays so that NaNs yield NaNs

import numpy as np

I have two arrays:

a = np.array([1,2,3,np.nan,5])
b = np.array([3,2,np.nan,5,4])

I would like to compare the elements in these two arrays & get a list of booleans as result. When there is nan involved in the comparison, I'd like to get nan. Expected result:

[False, False, nan, nan, True]

I have achieved the desired output using an if-else involving list comprehension:

[eacha>eachb
 if ~np.isnan(eacha) and ~np.isnan(eachb)
 else np.nan
 for eacha, eachb in zip(a,b)]

Is there a better (ie not involving for loop, if-else statements) way of doing this?

Upvotes: 1

Views: 123

Answers (2)

zabop
zabop

Reputation: 7852

To change Quang Hoang's excellent answer's output from floats to booleans, we can use pandas.Series.replace:

pd.Series(np.where(np.isnan(a)|np.isnan(b), np.nan, a==b)).replace({0:False,1:True}).to_numpy()

resulting in:

0    False
1     True
2      NaN
3      NaN
4    False
dtype: object

or:

pd.Series(np.where(np.isnan(a)|np.isnan(b), np.nan, a==b)).replace({0:False,1:True}).to_numpy()

resulting in:

array([False, True, nan, nan, False], dtype=object)

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150755

You can try:

np.where(np.isnan(a)|np.isnan(b), np.nan, a==b)

But then you get a float array, since np.nan is float:

array([ 0.,  1., nan, nan,  0.])

Upvotes: 4

Related Questions