Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find maximum value in whole 2D array with indices [duplicate]

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.

like image 980
Max Avatar asked Mar 21 '19 15:03

Max


People also ask

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

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.

How do you find the index of the maximum value in a 2D array Python?

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

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

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.


1 Answers

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)
like image 89
Chandrika Joshi Avatar answered Sep 20 '22 14:09

Chandrika Joshi