Get the position of the largest value in a multi-dimensional NumPy array

PythonArraysIndexingNumpy

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

(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)

Solution 3 - Python

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)

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkameView Question on Stackoverflow
Solution 1 - PythonManoj GovindanView Answer on Stackoverflow
Solution 2 - PythonotterbView Answer on Stackoverflow
Solution 3 - PythoniFederxView Answer on Stackoverflow
Solution 4 - Pythonuser13959036View Answer on Stackoverflow