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

U2E*_*EF1 5 python numpy

是否有一个numpy函数将转换像:

[0, 1, 0, 1, 1, 1, 0, 1, 1]
Run Code Online (Sandbox Code Playgroud)

到连续范围的起始/结束对数组,如:

[[1, 2],
 [3, 6],
 [7, 9]]
Run Code Online (Sandbox Code Playgroud)

Jai*_*ime 2

与 @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)
Run Code Online (Sandbox Code Playgroud)