阈值numpy数组,找到窗口

rco*_*oup 6 python arrays numpy

输入数据是一个二维数组(时间戳,值)对,按时间戳排序:

np.array([[50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66],
          [ 2,  3,  5,  6,  4,  2,  1,  2,  3,  4,  5,  4,  3,  2,  1,  2,  3]])
Run Code Online (Sandbox Code Playgroud)

我想找到值超过阈值的时间窗口(例如> = 4).似乎我可以使用布尔条件执行阈值部分,并使用以下内容映射回时间戳np.extract():

>>> a[1] >= 4
array([False, False,  True,  True,  True, False, False, False, False,
        True,  True,  True, False, False, False, False, False])

>>> np.extract(a[1] >= 4, a[0])
array([52, 53, 54, 59, 60, 61])
Run Code Online (Sandbox Code Playgroud)

但是从那里我需要每个窗口的第一个和最后一个时间戳匹配阈值(即.[[52, 54], [59, 61]]),这是我无法找到正确方法的地方.

Kas*_*mvd 6

这是一种方式:

# Create a mask
In [42]: mask = (a[1] >= 4)
# find indice of start and end of the threshold 
In [43]: ind = np.where(np.diff(mask))[0]
# add 1 to starting indices
In [44]: ind[::2] += 1
# find and reshape the result
In [45]: result = a[0][ind].reshape(-1, 2)

In [46]: result
Out[46]: 
array([[52, 54],
       [59, 61]])
Run Code Online (Sandbox Code Playgroud)