给定一维值数组:

A = [x,..,x,0,..,0,x,..,x,0,..,0,x,..,x,........]

哪里:

x,..,x代表任意数量的任意值



0,..,0代表任意数量的零

我需要找到一种快速算法来找到边界的索引
 即:..,x,0,..和..,0,x ..

这个问题似乎有助于并行化,但这超出了我的经验,因为随着数据量的增加,遍历数组的简单循环会变慢

谢谢
马丁

最佳答案

@chthonicdaemon的答案可以帮助您解决90%的问题,但是,如果您实际上想使用索引来切分数组,则需要一些其他信息。

大概是要使用索引来提取不为0的数组区域。您已经找到了数组更改的索引,但是您不知道更改是否是从TrueFalse或相反的方式。因此,您需要检查第一个和最后一个值并进行相应调整。否则,在某些情况下,您将提取零段而不是数据。

例如:

import numpy as np

def contiguous_regions(condition):
    """Finds contiguous True regions of the 1D boolean array "condition".
    Returns a 2D array where the first column is the start index of the region
    and the second column is the end index."""
    # Find the indicies of changes in "condition"
    idx = np.flatnonzero(np.diff(condition)) + 1

    # Prepend or append the start or end indicies to "idx"
    # if there's a block of "True"'s at the start or end...
    if condition[0]:
        idx = np.append(0, idx)
    if condition[-1]:
        idx = np.append(idx, len(condition))

    return idx.reshape(-1, 2)

# Generate an example dataset...
t = np.linspace(0, 4*np.pi, 20)
x = np.abs(np.sin(t)) + 0.1
x[np.sin(t) < 0.5] = 0

print x

# Get the contiguous regions where x is not 0
for start, stop in contiguous_regions(x != 0):
    print x[start:stop]


因此,在这种情况下,我们的示例数据集如下所示:

array([ 0.        ,  0.71421271,  1.06940027,  1.01577333,  0.        ,
        0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
        0.        ,  0.93716648,  1.09658449,  0.83572391,  0.        ,
        0.        ,  0.        ,  0.        ,  0.        ,  0.        ])


并通过执行以下操作:

for start, stop in contiguous_regions(x != 0):
    print x[start:stop]


我们会得到:

[ 0.71421271  1.06940027  1.01577333]
[ 0.93716648  1.09658449  0.83572391]

关于python - Numpy检测区域边界,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22592764/

10-11 04:49
查看更多