Argmax of numpy array returning non-flat indices Argmax of numpy array returning non-flat indices python python

Argmax of numpy array returning non-flat indices


You could use numpy.unravel_index() on the result of numpy.argmax():

>>> a = numpy.random.random((10, 10))>>> numpy.unravel_index(a.argmax(), a.shape)(6, 7)>>> a[6, 7] == a.max()True


np.where(a==a.max())

returns coordinates of the maximum element(s), but has to parse the array twice.

>>> a = np.array(((3,4,5),(0,1,2)))>>> np.where(a==a.max())(array([0]), array([2]))

This, comparing to argmax, returns coordinates of all elements equal to the maximum. argmax returns just one of them (np.ones(5).argmax() returns 0).


To get the non-flat index of all occurrences of the maximum value, you can modify eumiro's answer slightly by using argwhere instead of where:

np.argwhere(a==a.max())>>> a = np.array([[1,2,4],[4,3,4]])>>> np.argwhere(a==a.max())array([[0, 2],       [1, 0],       [1, 2]])