Removing NaNs in numpy arrays

I have two numpy arrays containing NaN:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([   1  ,   2,     3   ,   4,  np.nan])

Is there any smart way to use numpy to remove NaN in both arrays and also delete something at the corresponding index in another list? Do it like this:

A = array([  2,   3, ])
B = array([  2,   4, ])
+4
source share
2 answers

What you can do is add 2 arrays together, this will be overwritten using NaN values ​​where they are not, then use this to create an index of a boolean mask, and then use the index to index into the numpy source arrays:

In [193]:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([   1  ,   2,     3   ,   4,  np.nan])
idx = np.where(~np.isnan(A+B))
idx
print(A[idx])
print(B[idx])
[ 2.  3.]
[ 2.  4.]

output from A+B:

In [194]:

A+B
Out[194]:
array([ nan,   4.,  nan,   7.,  nan])

EDIT

@Oliver W., np.where , np.isnan , :

In [199]:

A = np.array([np.nan,   2,   np.nan,   3,   4])
B = np.array([   1  ,   2,     3   ,   4,  np.nan])
idx = (~np.isnan(A+B))
print(A[idx])
print(B[idx])
[ 2.  3.]
[ 2.  4.]
+8

A[~(np.isnan(A) | np.isnan(B))]

B[~(np.isnan(A) | np.isnan(B))]

+8

All Articles