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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With