这是另一种可能性:
import numpy as np
nan = np.nan
def using_clump(a):
return [a[s] for s in np.ma.clump_unmasked(np.ma.masked_invalid(a))]
x = [nan,nan, 1 , 2 , 3 , nan, nan, 10, 11 , nan, nan, nan, 23, 1, nan, 7, 8]
In [56]: using_clump(x)
Out[56]:
[array([ 1., 2., 3.]),
array([ 10., 11.]),
array([ 23., 1.]),
array([ 7., 8.])]
一些比较 using_clump 和 using_groupby 的基准测试:
import itertools as IT
groupby = IT.groupby
def using_groupby(a):
return [list(v) for k,v in groupby(a,np.isfinite) if k]
In [58]: %timeit using_clump(x)
10000 loops, best of 3: 37.3 us per loop
In [59]: %timeit using_groupby(x)
10000 loops, best of 3: 53.1 us per loop
对于较大的阵列,性能甚至更好:
In [9]: x = x*1000
In [12]: %timeit using_clump(x)
100 loops, best of 3: 5.69 ms per loop
In [13]: %timeit using_groupby(x)
10 loops, best of 3: 60 ms per loop