Reputation: 6107
How do I find the row or column which contains the array-wide maximum value in a 2d numpy array?
Upvotes: 20
Views: 48594
Reputation: 550
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.
Upvotes: 0
Reputation: 141
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]
Upvotes: 4
Reputation: 157484
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.
Upvotes: 24
Reputation: 36071
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)
Upvotes: 27
Reputation: 86326
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.
Upvotes: 21