[Numpy-discussion] how to do this efficiently?
Wed Feb 9 10:39:03 CST 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
This is similar to Zachary's as it just uses 'np.where'.
array([5, 4, 3, 6, 7, 3, 2, 1])
>>> np.argmax(x>5) # doesn't appear to be correct
>>> np.where(x>5)[-1]#since np.where gives a tuple and you need the
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).
More information about the NumPy-Discussion