【问题标题】:Threshold numpy array, find windows阈值numpy数组,查找窗口
【发布时间】:2019-01-08 10:05:11
【问题描述】:

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

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]])

我想找到值超过阈值的时间窗口(例如 >=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])

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

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    这是一种方法:

    # 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]])
    

    【讨论】:

    • 太好了! np.diff() 是一个不错的方法。
    • 如果数组中的最后一项匹配,ind 会以奇数个元素结束,并且 reshape 会失败并出现 ValueError: cannot reshape array of size 4321 into shape (2). 错误。在这种情况下将len(a)-1 附加到ind 会修复它(对于这个用例),因此最终窗口以数据集的结尾结束。
    【解决方案2】:

    当您拥有array([52, 53, 54, 59, 60, 61]) 时,您可以按照以下方式使用numpy.split

    a = np.array([52,53,54,59,60,61])
    b = list(a)
    indices = [inx for inx,j in enumerate([i[1]-i[0] for i in zip(b,b[1:])]) if j>1]
    suba = np.split(a,indices)
    print(suba) #prints [array([52, 53]), array([54, 59, 60, 61])]
    

    请注意,您应该将起点作为第二个参数提供给 numpy.split - 在此示例中,索引是 [2](包含一个值的列表)

    【讨论】:

      猜你喜欢
      • 2018-04-21
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 2017-07-10
      • 2011-04-23
      • 1970-01-01
      相关资源
      最近更新 更多