How do I find the row or column which contains the array-wide maximum value in a 2d numpy array?
5 Answers
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 Comments
np.argmax(np.max(x, axis=1)) is not comparable with this way in terms of performance; It is the fastest.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
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.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
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
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.