Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 445
kame Avatar asked Aug 27 '10 12:08

kame


People also ask

How do you find the maximum value of a 2D array NumPy?

You can use argmax() to get the index of your maximum value. Then you just have to compute this value to get the line and column indices.

How do you find the index of the maximum value in an array in Python?

index() functions to find out the index of the maximum value in a list. Use the enumerate() function to find out the index of the maximum value in a list. Use the numpy. argmax() function of the NumPy library to find out the index of the maximum value in a list.


2 Answers

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) 
like image 198
Manoj Govindan Avatar answered Oct 05 '22 22:10

Manoj Govindan


(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) 
like image 33
otterb Avatar answered Oct 05 '22 22:10

otterb