python - 区域边界的 Numpy 检测

标签 python numpy

给定一个一维值数组:

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

哪里:

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

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

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

这个问题似乎适合并行化,但这超出了我的经验,简单的遍历数组会因为数据太大而变慢

谢谢 马丁

最佳答案

@chthonicdaemon 的回答让您完成了 90% 的工作,但如果您真的想使用索引来分割数组,则需要一些额外的信息。

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

例如:

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/

相关文章:

python - 为什么 numpy 数组的元素与它们自己不一样?

python - 在 Python Flask 中使用 send_file 发送视频时手机出现错误

Python:实例没有属性

python - 从数组中选择特定元素

python - 神经网络训练平台中的梯度下降

python - python可以做高斯拟合和外推吗?

pandas - 为什么我在使用 polyfit 函数时得到 "ValueError: data type <class ' numpy.object _'> not inexact."?

python - 什么是函数接口(interface)(在 Python 中)?

python - 在 Django 中提交表单后停止页面重定向

python - 在 Windows 10 上安装 cassandra 3.10