Skip to content Skip to sidebar Skip to footer

How To Filter Out Subarrays Which Contain NaN's?

Let's assume an array of shape (n,5,2) which contains NaNs at random places, generated by the following code: n = 10 arr = np.random.rand(n, 5, 2) # replace some values by nan arr

Solution 1:

No need to reshape anything:

has_nans = np.isnan(arr).any(axis=(-1,-2))
has_nans 
array([False, False, False,  True,  True,  True, False, False, False,  True], dtype=bool)

>>> arr = arr[~has_nans]
>>> arr.shape
(6, 5, 2)

Older versions of numpy you will need to do something like the following:

has_nans = np.isnan(arr).any(axis=-1).any(axis=-1)

Solution 2:

This is a 1 liner:

new = arr[~np.isnan(arr).any((-1,-2))]

print new.shape
Out[10]: (5, 5, 2)

Post a Comment for "How To Filter Out Subarrays Which Contain NaN's?"