[Numpy-discussion] how to do this efficiently?

Bruce Southey bsouthey at gmail.com
Wed Feb 9 11:39:03 EST 2011


On 02/09/2011 10:17 AM, Zachary Pincus wrote:
>>> 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?
>> This assumes monotonicity. Is that allowed?
> The twice-stated problem was:
>
>> In a 1-d array, find the first point where all subsequent points
>> have values less than a threshold, T.
> So that should do the trick... Though Alan's argmax solution is
> definitely a better one than indexing an indices array. Same logic and
> result though, just more compact.
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
This is similar to Zachary's as it just uses 'np.where'.

 >>> x=np.array([5,4,3,6,7,3,2,1])
 >>> x
array([5, 4, 3, 6, 7, 3, 2, 1])
 >>> np.argmax(x>5) # doesn't appear to be correct
3
 >>> np.where(x>5)[0][-1]#since np.where gives a tuple and you need the 
last element
4


This should give the index where all subsequent points are less than 
some threshold. However, this and  Zachary's version fail when if all 
points are lower than the threshold (eg T=10 in this array).

Bruce



More information about the NumPy-Discussion mailing list