Reputation: 7852
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
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
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