【问题标题】:Find array position greater than a threshold where the next position is less than the threshold (numpy)查找大于阈值的数组位置,其中下一个位置小于阈值(numpy)
【发布时间】:2018-01-25 23:04:41
【问题描述】:

有没有一种有效的方法来返回数组位置,其中给定位置的值大于阈值并且后续位置小于该阈值?我可以在一个循环中完成此操作,但对于具有 100,000 多个条目的数组来说非常慢。

举个例子,

x=[4,9,1,5,7,8,10,11,2,4]

threshold=3

# find elements greater than 3 and where the next element is less than 3

return [1,7] #corresponding to indexes for values 9 and 11 in x

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:
    • x[:-1] > threshold:查看当前值
    • x[1:] < threshold:检查下一个值
    • np.flatnonzero:获取真实指数

    x = np.array([4,9,1,5,7,8,10,11,2,4])
    ​
    np.flatnonzero((x[:-1] > threshold) & (x[1:] < threshold))
    # array([1, 7])
    

    【讨论】:

      【解决方案2】:

      你可以使用这个解决方案

      In [148]: x
      Out[148]: array([ 4,  9,  1,  5,  7,  8, 10, 11,  2,  4])
      
      # masks for satisfying your condition
      In [149]: gt = x>3
      In [150]: lt = x[1:]<3
      
      # multiply the boolean masks and find the indices of `True` values
      In [151]: np.where(gt[:-1] * lt)
      Out[151]: (array([1, 7]),)
      
      # return indices as an array
      In [152]: np.where(gt[:-1] * lt)[0]
      Out[152]: array([1, 7])
      

      【讨论】:

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