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.
Approach: The idea is to traverse the matrix using two nested loops, one for rows and one for columns, and find the maximum element. Initialize a variable maxElement with a minimum value and traverse the matrix and compare every time if the current element is greater than a maxElement.
You can use argmax() to get the index of your maximum value.
To find maximum value from complete 2D numpy array we will not pass axis in numpy. amax() i.e. It will return the maximum value from complete 2D numpy arrays i.e. in all rows and columns.
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)
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