创建“条纹"的开始和结束索引的2D numpy数组.在另一个数组中. [英] Creating 2D numpy array of start and end indices of "streaks" in another array.

查看:72
本文介绍了创建“条纹"的开始和结束索引的2D numpy数组.在另一个数组中.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数字myArray = ([1, 1, 0, 2, 0, 1, 1, 1, 1, 0, 0 ,1, 2, 1, 1, 1])的一维numpy数组.

Say I have a 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的任何条纹"(长于2)的第一个(列1)和最后一个(列2)索引. 因此,对于上面的示例,二维数组应如下所示:

I want to create a 2D numpy array that describe the first (column 1) and last (column 2) indices of any "streak" of consecutive 1's that is longer than 2. So for the example above, the 2D array should look like this:

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

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

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

Since there are at least 3 consecutive ones in the 5th, 6th, 7th, 8th places and in the 13th, 14th, 15th places.

任何帮助将不胜感激.

推荐答案

方法1

这是一种受 this post -

Here's one approach inspired by 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 -

Another with 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]

这篇关于创建“条纹"的开始和结束索引的2D numpy数组.在另一个数组中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆