且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在numpy数组中找到大量满足条件的连续值

更新时间:2022-12-10 20:49:14

这是一个基于 numpy 的解决方案.

Here's a numpy-based solution.

我认为 (?) 它应该比其他选项更快.希望它相当清楚.

I think (?) it should be faster than the other options. Hopefully it's fairly clear.

然而,它需要的内存是各种基于生成器的解决方案的两倍.只要您可以在内存中保存数据的单个临时副本(用于差异),以及与数据长度相同的布尔数组(每个元素 1 位),它应该非常有效......

However, it does require a twice as much memory as the various generator-based solutions. As long as you can hold a single temporary copy of your data in memory (for the diff), and a boolean array of the same length as your data (1-bit-per-element), it should be pretty efficient...

import numpy as np

def main():
    # Generate some random data
    x = np.cumsum(np.random.random(1000) - 0.5)
    condition = np.abs(x) < 1
    
    # Print the start and stop indices of each region where the absolute 
    # values of x are below 1, and the min and max of each of these regions
    for start, stop in contiguous_regions(condition):
        segment = x[start:stop]
        print start, stop
        print segment.min(), segment.max()

def contiguous_regions(condition):
    """Finds contiguous True regions of the 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"
    d = np.diff(condition)
    idx, = d.nonzero() 

    # We need to start things after the change in "condition". Therefore, 
    # we'll shift the index by 1 to the right.
    idx += 1

    if condition[0]:
        # If the start of condition is True prepend a 0
        idx = np.r_[0, idx]

    if condition[-1]:
        # If the end of condition is True, append the length of the array
        idx = np.r_[idx, condition.size] # Edit

    # Reshape the result into two columns
    idx.shape = (-1,2)
    return idx

main()