我们可以做这样的事情,适用于任何通用数组-
def islandinfo(y, trigger_val, stopind_inclusive=True): # Setup "sentients" on either sides to make sure we have setup # "ramps" to catch the start and stop for the edge islands # (left-most and right-most islands) respectively y_ext = np.r_[False,y==trigger_val, False] # Get indices of shifts, which represent the start and stop indices idx = np.flatnonzero(y_ext[:-1] != y_ext[1:]) # Lengths of islands if needed lens = idx[1::2] - idx[:-1:2] # Using a stepsize of 2 would get us start and stop indices for each island return list(zip(idx[:-1:2], idx[1::2]-int(stopind_inclusive))), lens
样品运行-
In [320]: yOut[320]: array([1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1])In [321]: islandinfo(y, trigger_val=1)[0]Out[321]: [(0, 2), (8, 9), (16, 19)]In [322]: islandinfo(y, trigger_val=0)[0]Out[322]: [(3, 7), (10, 15)]
另外,我们可以使用
diff来获取切片后的比较结果,然后简单地用
2列进行整形以替换步长大小的切片,从而给自己一个单线-
In [300]: np.flatnonzero(np.diff(np.r_[0,y,0])!=0).reshape(-1,2) - [0,1]Out[300]: array([[ 0, 2], [ 8, 9], [16, 19]])



