【问题标题】:Creating 2D numpy array of start and end indices of "streaks" in another array.在另一个数组中创建“条纹”的开始和结束索引的 2D numpy 数组。
【发布时间】:2018-07-10 15:21:35
【问题描述】:

假设我有一个 1D numpy 数字数组 myArray = ([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0 ,1, 2, 1, 1, 1])

我想创建一个 2D numpy 数组,该数组描述任何长于 2 的连续 1 的“条纹”的第一个(第 1 列)和最后一个(第 2 列)索引。 所以对于上面的例子,二维数组应该是这样的:

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

因为第 5、6、7、8 位和第 13、14、15 位至少有 3 个连续的。

任何帮助将不胜感激。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    方法#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]
    

    【讨论】:

    • 干杯!像魅力一样工作。
    猜你喜欢
    • 2019-03-02
    • 2022-07-08
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2011-07-27
    • 2021-06-12
    相关资源
    最近更新 更多