识别1D numpy数组中所有连续的正三元组



考虑如下所示的1D数组arr,并假设n = 3。我想确定所有拥有>= n个连续正值的"岛屿"。

下面的代码成功找到了FIRST由3个连续正数组成的集合,通过确定初始索引,但它没有找到所有这样的集合.
import numpy as np
arr = np.array([1, -1, 5, 6, 3, -4, 2, 5, 9, 2, 1, -6, 8])
def find_consec_pos(arr, n):
mask = np.convolve(np.greater(arr,0), np.ones(n, dtype=int)) >= n
if mask.any():
return mask.argmax() - n + 1
else:
return None

find_consec_pos(arr, 3)

这给出了输出2,连续正值的第一个三元组的索引。
我想知道如何修改代码以获得输出[2, 6, 7, 8],识别所有连续的正三元组。

这段代码完成了这个任务,它简单而又相对高效:

positive = arr > 0
np.where(positive[:-2] & positive[1:-1] & positive[2:])

您可以使用sliding_window_view:

In [1]: from numpy.lib.stride_tricks import sliding_window_view
In [2]: sliding_window_view(arr, 3) > 0
Out[2]:
array([[ True, False,  True],
[False,  True,  True],
[ True,  True,  True],
[ True,  True, False],
[ True, False,  True],
[False,  True,  True],
[ True,  True,  True],
[ True,  True,  True],
[ True,  True,  True],
[ True,  True, False],
[ True, False,  True]])

把它变成你想要的函数(假设你想要一个list作为输出):

def find_consec_pos(arr, n):
all_n_positive = np.all(sliding_window_view(arr > 0, n), axis=1)
return np.argwhere(all_n_positive).flatten().tolist()

不同窗口的演示大小:

In [4]: arr
Out[4]: array([ 1, -1,  5,  6,  3, -4,  2,  5,  9,  2,  1, -6,  8])
In [5]: find_consec_pos(arr, 3)
Out[5]: [2, 6, 7, 8]
In [6]: find_consec_pos(arr, 4)
Out[6]: [6, 7]
In [7]: find_consec_pos(arr, 2)
Out[7]: [2, 3, 6, 7, 8, 9]

最新更新