[Numpy-discussion] how to do this efficiently?

Zachary Pincus zachary.pincus at yale.edu
Wed Feb 9 13:18:18 EST 2011

>>> In a 1-d array, find the first point where all subsequent points  
>>> have values
>>> less than a threshold.
> This doesn't imply monotonicity.
> Suppose with have a sin curve, and I want to find the last trough. Or
> a business cycle and I want to find the last recession.
> Unless my english deteriorated recently.

Not sure that I follow? I read the statement as:
find the smallest non-negative index i such that array[j] < t for all  
i <= j < len(array)

for which the various solutions proposed work, except for the corner  
case where array.min() >= t.

I'm not sure where monotonicity comes into play, unless one interprets  
the "all subsequent points" clause as "some number of subsequent  
points" or something...

For those sort of problems, I usually wind up smoothing the array  
[optional], and then using scipy.ndimage.maximum to calculate peak  
values within a given window, and then find the points that equal the  
peak values -- this works pretty robustly for peak/trough detection in  
arbitrary dimension.

More information about the NumPy-Discussion mailing list