Python 将布尔索引转换为运行的开始/结束对

Python 将布尔索引转换为运行的开始/结束对,python,numpy,Python,Numpy,是否有一个numpy函数可以转换如下内容: [0, 1, 0, 1, 1, 1, 0, 1, 1] 到连续范围的开始/结束对数组,如下所示: [[1, 2], [3, 6], [7, 9]] 不幸的是,我没有安装numpy,但是这个逻辑应该可以帮你 import itertools x = [0, 1, 0, 1, 1, 1, 0, 1, 1] # get the indices where 1->0 and 0->1 diff = np.diff(x) diff_ind

是否有一个numpy函数可以转换如下内容:

[0, 1, 0, 1, 1, 1, 0, 1, 1]
到连续范围的开始/结束对数组,如下所示:

[[1, 2],
 [3, 6],
 [7, 9]]

不幸的是,我没有安装numpy,但是这个逻辑应该可以帮你

import itertools
x = [0, 1, 0, 1, 1, 1, 0, 1, 1]

# get the indices where 1->0 and 0->1
diff = np.diff(x) 
diff_index = diff.nonzero(x)

# pair up the ranges using itertools
def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

ranges = pairwise(x)
文件:


结果:

>>> find_starts_ends(a)
array([[1, 2],
       [3, 6],
       [7, 9]])
>>> find_starts_ends([1,1,0,0,1,1])
array([[0, 2],
       [4, 6]])

使用与@Serdalis答案相同的原则,但仅依赖numpy:

def start_end(arr):
    idx = np.nonzero(np.diff(arr))[0] + 1
    if arr[0]:
        idx = np.concatenate((np.array([0], dtype=np.intp), idx))
    if arr[-1]:
        idx = np.concatenate((idx, np.array([len(arr)],
                                            dtype=np.intp),))
    return idx.reshape(-1, 2)

>>> start_end([1,1,1,0,0,1,0])
array([[0, 3],
       [5, 6]], dtype=int64)
>>> start_end([0,1,1,1,0,0,1])
array([[1, 4],
       [6, 7]], dtype=int64)
>>> start_end([0,1,1,1,0,0,1,0])
array([[1, 4],
       [6, 7]], dtype=int64)
>>> start_end([1,1,1,0,0,1])
array([[0, 3],
       [5, 6]], dtype=int64)

嗯,这很接近工作了。Diff显然是一种解决方法。但是不能有列表理解。好了,没有列表理解,它确实返回了一个izip对象。谢谢,@Jaime,我修复了它。应该说
temp=np.concatenate([[0],x,[0]])
,但其他方面几乎就是我得到的结果。
def start_end(arr):
    idx = np.nonzero(np.diff(arr))[0] + 1
    if arr[0]:
        idx = np.concatenate((np.array([0], dtype=np.intp), idx))
    if arr[-1]:
        idx = np.concatenate((idx, np.array([len(arr)],
                                            dtype=np.intp),))
    return idx.reshape(-1, 2)

>>> start_end([1,1,1,0,0,1,0])
array([[0, 3],
       [5, 6]], dtype=int64)
>>> start_end([0,1,1,1,0,0,1])
array([[1, 4],
       [6, 7]], dtype=int64)
>>> start_end([0,1,1,1,0,0,1,0])
array([[1, 4],
       [6, 7]], dtype=int64)
>>> start_end([1,1,1,0,0,1])
array([[0, 3],
       [5, 6]], dtype=int64)