20

How do I find the row or column which contains the array-wide maximum value in a 2d numpy array?

5 Answers 5

27

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This is the most efficient solution here proposed.
np.argmax(np.max(x, axis=1)) is not comparable with this way in terms of performance; It is the fastest.
24

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.

3 Comments

this works perfect for integer elements but what for float ?
argmax doesn't return the array-wide maximum index, it only computes it across the axis. np.argmax(np.max(x, axis=1)) computes the the maximums for each row, across the columns. Not array wide.
Wrong answer! Consider the example: [[0,1],[1,0]]. The code returns column=0, row=0. But 0 - is not the maximum in the matrix
21

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.

1 Comment

this can return more than 1 value if there is a tie
4

np.argmax just returns the index of the (first) largest element in the flattened array. So if you know the shape of your array (which you do), you can easily find the row / column indices:

A = np.array([5, 6, 1], [2, 0, 8], [4, 9, 3])
am = A.argmax()
c_idx = am % A.shape[1]
r_idx = am // A.shape[1]

Comments

0

You can use np.argmax() directly.

The example is copied from the official documentation.

>>> a = np.arange(6).reshape(2,3) + 10
>>> a
array([[10, 11, 12],
       [13, 14, 15]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])

axis = 0 is to find the max in each column while axis = 1 is to find the max in each row. The returns is the column/row indices.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.