19

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)
2
  • 1
    This is the most efficient solution here proposed. Jan 2, 2020 at 14:17
  • np.argmax(np.max(x, axis=1)) is not comparable with this way in terms of performance; It is the fastest.
    – Ali_Sh
    Apr 6, 2022 at 2:43
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
  • this works perfect for integer elements but what for float ? Feb 23, 2019 at 8:22
  • 1
    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. Nov 12, 2021 at 21:22
  • 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
    – gudasergey
    Apr 5 at 8:13
20

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
  • 3
    this can return more than 1 value if there is a tie Feb 9, 2019 at 2:50
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]
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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.