Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the argmax of a two dimensional array in numpy?

Tags:

python

numpy

I have a numpy ndarray:

array = np.array([[1,2,3],[4,5,6],[7,8,9]])

Whenever I do, np.argmax(array), it doesn't return a tuple of row and column. Why not?

like image 708
Asker123 Avatar asked Dec 09 '17 06:12

Asker123


1 Answers

You didn't specify an axis. It returns an index into the flattened array, as documented.

>>> L = [[1,2,3],[4,5,6],[7,8,9]]
>>> np.argmax(L)
8
>>> np.array(L).ravel()[np.argmax(L)]
9

If you want to get the row and column from that index, unravel it:

>>> np.unravel_index(8, np.array(L).shape)
(2, 2)
like image 172
wim Avatar answered Sep 21 '22 10:09

wim