如何在2d numpy数组中找到包含数组范围最大值的行或列?
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.
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)
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]
You can use np.argmax()
directly.
The example is copied from the official documentation .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.