如何从包含NaN的数组中提取连续元素

Jun*_*hen 10 python numpy

考虑下面的numpy数组

x = np.array([1, 2, np.nan, np.nan, 3, 4, 5, np.nan])
Run Code Online (Sandbox Code Playgroud)

我想提取其中所有非NaN连续元素,x并且预期的输出是列表

y = [[1, 2],[3, 4, 5]]
Run Code Online (Sandbox Code Playgroud)

他们有没有比简单for循环既优雅又快速的方法?

Tra*_*man 5

使用 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]]
Run Code Online (Sandbox Code Playgroud)