find row or column containing maximum value in numpy array

You can use np.where(x == np.max(x)).

For example:

>>> x = np.array([[1,2,3],[2,3,4],[1,3,1]])
>>> x
array([[1, 2, 3],
       [2, 3, 4],
       [1, 3, 1]])
>>> np.where(x == np.max(x))
(array([1]), array([2]))

The first value is the row number, the second number is the column number.


You can use np.argmax along with np.unravel_index as in

x = np.random.random((5,5))
print np.unravel_index(np.argmax(x), x.shape)

If you only need one or the other:

np.argmax(np.max(x, axis=1))

for the column, and

np.argmax(np.max(x, axis=0))

for the row.

Tags:

Python

Numpy