Is there an efficient way to return array positions where the value in a given position is greater than a threshold value AND the subsequent position is less than that threshold? I am able to accomplish this in a loop, but it is very slow for arrays with 100,000+ entries.
是否有一种有效的方法来返回给定位置的值大于阈值并且后续位置小于该阈值的数组位置?我能够在一个循环中实现这一点,但对于具有100,000多个条目的数组来说它非常慢。
As an example,
举个例子,
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
2 个解决方案
#1
1
-
x[:-1] > threshold
: check the current value -
x[1:] < threshold
: check the next value -
np.flatnonzero
: get the true indices
x [: - 1]>阈值:检查当前值
x [1:] <阈值:检查下一个值< p>
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
0
You can use this solution
您可以使用此解决方案
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])
#1
1
-
x[:-1] > threshold
: check the current value -
x[1:] < threshold
: check the next value -
np.flatnonzero
: get the true indices
x [: - 1]>阈值:检查当前值
x [1:] <阈值:检查下一个值< p>
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
0
You can use this solution
您可以使用此解决方案
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])