首页 > 解决方案 > 在另一个数组中创建“条纹”的开始和结束索引的二维 numpy 数组。

问题描述

假设我有一个 1D numpy array of numbers myArray = ([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0 ,1, 2, 1, 1, 1])

我想创建一个 2D numpy 数组,该数组描述任何连续 1 的“条纹”的第一个(第 1 列)和最后一个(第 2 列)索引,该索引的长度大于 2。因此对于上面的示例,二维数组应该如下所示:

indicesArray = ([5, 8], [13, 15])

由于第 5、6、7、8 位和第 13、14、15 位至少有 3 个连续出现。

任何帮助,将不胜感激。

标签: pythonnumpy

解决方案


方法#1

这是一种受以下启发的方法this post-

def start_stop(a, trigger_val, len_thresh=2):
    # "Enclose" mask with sentients to catch shifts later on
    mask = np.r_[False,np.equal(a, trigger_val),False]

    # Get the shifting indices
    idx = np.flatnonzero(mask[1:] != mask[:-1])

    # Get lengths
    lens = idx[1::2] - idx[::2]

    return idx.reshape(-1,2)[lens>len_thresh]-[0,1]

样品运行 -

In [47]: myArray
Out[47]: array([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0, 1, 2, 1, 1, 1])

In [48]: start_stop(myArray, trigger_val=1, len_thresh=2)
Out[48]: 
array([[ 5,  8],
       [13, 15]])

方法#2

另一个与binary_erosion-

from scipy.ndimage.morphology import binary_erosion

mask = binary_erosion(myArray==1,structure=np.ones((3)))
idx = np.flatnonzero(mask[1:] != mask[:-1])
out = idx.reshape(-1,2)+[0,1]

推荐阅读