Numpy查找具有相同值的组的索引
问题内容:
我有一个零和一的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)
我还在这里找到了部分解决方案:
查找元素更改值numpy的索引
但这只是给我提供值更改的索引。
问题答案:
我们可以做这样的事情,适用于任何通用数组-
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]: 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]])