Find a range of length N in a numpy array where some condition is true

I have a (numpy) array representing a measurement curve. I am looking for the first index i, after which subsequent elements Nsatisfy some condition, for example. lie within certain limits. In pseudo-code words, I'm looking for a minimum isuch that

lower_bound < measurement[i:i+N] < higher_bound

performed for all elements in the range.

Of course, I could do the following:

for i in xrange(len(measurement) - N):
    test_vals = measurement[i:i + N]
    if all([True if lower_bound < x < higher_bound else False for x in test_vals]):
        return i

This is extremely inefficient as I always compare the values Nfor each i. What is the most pythonic way to achieve this? Has Numpy some built-in features to find this?

EDIT: As requested, I provide some sample input

a = [1,2,3,4,5,5,6,7,8,5,4,5]
lower_bound = 3.5
upper_bound = 5.5 
N = 3

3, a[3], 3 .

+4
3

NumPythonic measurement, 2D-, 2D- measurement. np.all(..axis=1) . , . - -

m2D = measurement[np.arange(N) + np.arange(len(measurement)-N+1)[:,None]]
np.nonzero(np.all((lower_bound < m2D) & (higher_bound > m2D),axis=1))[0][0]

-

In [1]: measurement = np.array([1,2,3,4,5,5,6,7,8,5,4,5])
   ...: lower_bound = 3.5
   ...: higher_bound = 5.5 
   ...: N = 3
   ...: 

In [2]: m2D = measurement[np.arange(N) + np.arange(len(measurement)-N+1)[:,None]]

In [3]: m2D # Notice that is a 2D array (shifted) version of input
Out[3]: 
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 5],
       [5, 5, 6],
       [5, 6, 7],
       [6, 7, 8],
       [7, 8, 5],
       [8, 5, 4],
       [5, 4, 5]])

In [4]: np.nonzero(np.all((lower_bound < m2D) & (higher_bound > m2D),axis=1))[0][0]
Out[4]: 3
+3

M - a, O (M) -.

locations=(lower_bound<a) & (a<upper_bound)
cum=locations.cumsum()
lengths=np.roll(cum,-N)-cum==N
result=lengths.nonzero()[0][0]+1
+2

, numpy:

?

0

Source: https://habr.com/ru/post/1615720/


All Articles