Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find last occurrence of maximum value in a numpy.ndarray

Tags:

numpy

scipy

I have a numpy.ndarray in which the maximum value will mostly occur more than once.

EDIT: This is subtly different from numpy.argmax: how to get the index corresponding to the *last* occurrence, in case of multiple occurrences of the maximum values because the author says

Or, even better, is it possible to get a list of indices of all the occurrences of the maximum value in the array?

whereas in my case getting such a list may prove very expensive

Is it possible to find the index of the last occurrence of the maximum value by using something like numpy.argmax? I want to find only the index of the last occurrence, not an array of all occurrences (since several hundreds may be there)

For example this will return the index of the first occurrence ie 2

import numpy as np a=np.array([0,0,4,4,4,4,2,2,2,2]) print np.argmax(a) 

However I want it to output 5.

like image 296
Sudarshan S Avatar asked Jan 07 '12 09:01

Sudarshan S


People also ask

What does argmax do in NumPy?

The numpy. argmax() function returns indices of the max element of the array in a particular axis. Return : Array of indices into the array with same shape as array.

How do you find the highest value in an array in Python?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.


1 Answers

numpy.argmax only returns the index of the first occurrence. You could apply argmax to a reversed view of the array:

import numpy as np a = np.array([0,0,4,4,4,4,2,2,2,2]) b = a[::-1] i = len(b) - np.argmax(b) - 1 i     # 5 a[i:] # array([4, 2, 2, 2, 2]) 

Note numpy doesn't copy the array but instead creates a view of the original with a stride that accesses it in reverse order.

id(a) == id(b.base) # True 
like image 181
outis Avatar answered Sep 28 '22 20:09

outis