[Numpy-discussion] how to do this efficiently?

Neal Becker ndbecker2@gmail....
Wed Feb 9 10:48:25 CST 2011


Zachary Pincus wrote:

> 
> On Feb 9, 2011, at 10:58 AM, Neal Becker wrote:
> 
>> Zachary Pincus wrote:
>>
>>>>>> In a 1-d array, find the first point where all subsequent points
>>>>>> have values
>>>>>> less than a threshold, T.
>>>>>
>>>>> Maybe something like:
>>>>>
>>>>> last_greater = numpy.arange(arr.shape)[arr >= T][-1]
>>>>> first_lower = last_greater + 1
>>>>>
>>>>> There's probably a better way to do it, without the arange,
>>>>> though...
>>>>
>>>> I'm trying to find the first point in a power spectrum such that all
>>>> subsequent
>>>> points are below some level.  I've started with:
>>>>
>>>> db is my power spectrum in dB,   It is already reversed.
>>>>
>>>> mag = np.maximum.accumulate (db) - db[-1]
>>>>
>>>> Now all I need is to find the first point such that mag < -50.  How
>>>> to do this
>>>> efficiently?
>>>
>>> Right -- that's what I showed above. Find the last point in mag that
>>> is >= -50, and by definition the next point is the first point such
>>> that the remainder of mag is < -50.
>>
>> But where is numpy's 'find_first' function?  I can't seem to find it
>> so I had to
>> make my own in C++.
> 
> 
> As before, the line below does what you said you need, though not
> maximally efficiently. (Try it in an interpreter...) There may be
> another way in numpy that doesn't rely on constructing the index
> array, but this is the first thing that came to mind.
> 
> last_greater = numpy.arange(arr.shape)[arr >= T][-1]
> 
> Let's unpack that dense line a bit:
> 
> mask = arr >= T
> indices = numpy.arange(arr.shape)
> above_threshold_indices = indices[mask]
> last_above_threshold_index = above_threshold_indices[-1]
> 
> Does this make sense?

Yes, thanks for the explanation.

Still, I wonder if numpy would benefit from a 'find_first' function.



More information about the NumPy-Discussion mailing list