31

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.

Community
  • 1
  • 1
Sudarshan S
  • 1,235
  • 2
  • 16
  • 25
  • possible duplicate of [numpy.argmax: how to get the index corresponding to the *last* occurrence, in case of multiple occurrences of the maximum values](http://stackoverflow.com/questions/7038975/numpy-argmax-how-to-get-the-index-corresponding-to-the-last-occurrence-in-ca) – outis Jan 07 '12 at 09:55
  • 1
    The author there wants the index of all occurrences, and the solution given there `occurences = np.where(a == a.max())` will generate an array of all maximum values which may be very expensive in my case – Sudarshan S Jan 07 '12 at 10:10
  • though the answer addresses only how to get all occurrences, the questioner asked for both, hence "possible duplicate" rather than "duplicate". – outis Jan 07 '12 at 22:14

1 Answers1

70

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
outis
  • 75,655
  • 22
  • 151
  • 221
  • Is there no equivalent function that gets the index of the last occurrence? Also wont reversing the array be an O(n) operation, not to mention doubling memory usage? – Sudarshan S Jan 07 '12 at 09:49
  • 4
    Doubtful there's another function, since the reverse view is quite efficient. – outis Jan 07 '12 at 09:54