93

How can I get get the position (indices) of the largest value in a multi-dimensional NumPy array?

Trilarion
  • 9,942
  • 9
  • 61
  • 98
kame
  • 19,003
  • 30
  • 100
  • 149
  • 1
    In case there are multiple positions with equally large values, do you need them all or only the first (or last or just any)? – Trilarion Oct 21 '20 at 12:21

4 Answers4

190

The argmax() method should help.

Update

(After reading comment) I believe the argmax() method would work for multi dimensional arrays as well. The linked documentation gives an example of this:

>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3

Update 2

(Thanks to KennyTM's comment) You can use unravel_index(a.argmax(), a.shape) to get the index as a tuple:

>>> from numpy import unravel_index
>>> unravel_index(a.argmax(), a.shape)
(1, 0)
Community
  • 1
  • 1
Manoj Govindan
  • 68,439
  • 21
  • 129
  • 136
6

(edit) I was referring to an old answer which had been deleted. And the accepted answer came after mine. I agree that argmax is better than my answer.

Wouldn't it be more readable/intuitive to do like this?

numpy.nonzero(a.max() == a)
(array([1]), array([0]))

Or,

numpy.argwhere(a.max() == a)
otterb
  • 2,550
  • 2
  • 26
  • 46
  • 4
    Needlessly slow, because you compute the max and then compare it to all of a. unravel_index(a.argmax(), a.shape). – Peter Oct 24 '14 at 00:25
  • I voted for this because it assumes nothing about the number of occurrences of a.max() in a. Whereas a.argmax() will return the "first" occurrence (which is ill-defined in the case of a multi-dimensional array since it depends on the choice of traversal path). https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html#numpy.argmax I also think np.where() is a more natural/readable chose rather than np.nonzero(). – FizxMike Apr 24 '17 at 18:30
2

You can simply write a function (that works only in 2d):

def argmax_2d(matrix):
    maxN = np.argmax(matrix)
    (xD,yD) = matrix.shape
    if maxN >= xD:
        x = maxN//xD
        y = maxN % xD
    else:
        y = maxN
        x = 0
    return (x,y)
iFederx
  • 785
  • 10
  • 15
0

An alternative way is change numpy array to list and use max and index methods:

List = np.array([34, 7, 33, 10, 89, 22, -5])
_max = List.tolist().index(max(List))
_max
>>> 4