How can I get get the position (indices) of the largest value in a multi-dimensional NumPy array?
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.
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.
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)
(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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With