我有一个0和0的numpy数组:
y=[1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1]
我想计算一组(或零)的索引。因此,对于上面的示例,一组的结果应该类似于:
result=[(0,2), (8,9), (16,19)]
(怎么样)我可以用numpy做到吗?我没有发现像分组功能。
我尝试了np.ediff1d,但无法找到一个好的解决方案。并不是说数组可能会也可能不会以一组结果开始/结束:
import numpy as np
y = [1,1,1,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1,1,1]
mask = np.ediff1d(y)
starts = np.where(mask > 0)
ends = np.where(mask < 0)
我在这里也找到了部分解决方案: Find index where elements change value numpy
但那个只给了我改变值的指数。
答案 0 :(得分:5)
我们可以做这样的事情,适用于任何通用数组 -
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 zip(idx[:-1:2], idx[1::2]-int(stopind_inclusive)), lens
示例运行 -
In [320]: y
Out[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]])