Consider following numpy array
x = np.array([1, 2, np.nan, np.nan, 3, 4, 5, np.nan])
I want to extract all non-NaN consecutive elements in x
and the expected outputs is the list
y = [[1, 2],[3, 4, 5]]
Is their any method that is both elegant and faster than simple for
loop ?
To check for NaN values in a Numpy array you can use the np. isnan() method. This outputs a boolean mask of the size that of the original array. The output array has true for the indices which are NaNs in the original array and false for the rest.
using itertools.groupby
from itertools import groupby
result = [list(map(int,g)) for k,g in groupby(x, np.isnan) if not k]
print (result)
#[[1, 2], [3, 4, 5]]
You can use np.split
:
np.split(x, np.where(np.diff(np.isnan(x), prepend=True))[0])[1::2]
#[array([1., 2.]), array([3., 4., 5.])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With