是否有一种有效的方法来返回给定位置的值大于阈值并且后续位置小于该阈值的数组位置?我能够在一个循环中实现这一点,但对于具有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
答案 0 :(得分: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])
答案 1 :(得分:0)
您可以使用此解决方案
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])