22

I want to find the maximum value in a 2D array and the indices of the maximum value in Python using NumPy. I used

np.amax(array)

for searching for the maximum value, but I don't know how to get its indices. I could find it by using ´for` loops, but maybe there is a better way.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Max
  • 825
  • 2
  • 7
  • 7
  • 5
    This is not a duplicate of [How to get the index of a maximum element in a NumPy array along one axis](https://stackoverflow.com/questions/5469286/how-to-get-the-index-of-a-maximum-element-in-a-numpy-array-along-one-axis). The maximum of a 2D array is not the same as the maximum along some axes. – NoDataDumpNoContribution Oct 21 '20 at 12:14
  • 1
    It's a duplicate of [Get the position of the biggest item in a multi-dimensional numpy array](https://stackoverflow.com/questions/3584243/get-the-position-of-the-biggest-item-in-a-multi-dimensional-numpy-array) instead. – NoDataDumpNoContribution Oct 21 '20 at 12:17

3 Answers3

60

Refer to this answer, which also elaborates how to find the max value and its (1D) index, you can use argmax()

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

You can then use unravel_index(a.argmax(), a.shape) to get the indices as a tuple:

>>> from numpy import unravel_index
>>> unravel_index(a.argmax(), a.shape)
(1, 0)
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Chandrika Joshi
  • 1,211
  • 11
  • 24
3

Here, You can test the max value using the index returned, indices returned should look like (array([0], dtype=int64), array([2], dtype=int64)) when you print the indices.

import numpy as np
a = np.array([[200,300,400],[100,50,300]])
indices = np.where(a == a.max())
print(a[indices]) # prints [400]

# Index for max value found two times (two locations)
a = np.array([[200,400,400],[100,50,300]])
indices = np.where(a == a.max())
print(a[indices]) # prints [400 400] because two indices for max
#Now lets print the location (Index)
for index in indices:
    print(index)
BetaDev
  • 4,516
  • 3
  • 21
  • 47
-4

You can use argmax() to get the index of your maximum value.

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

It should return:

3

Then you just have to compute this value to get the line and column indices.

Best

Community
  • 1
  • 1
Maxouille
  • 2,729
  • 2
  • 19
  • 42