在numpy数组中查找包含最大值的行或列

41ik7eoe  于 12个月前  发布在  其他
关注(0)|答案(5)|浏览(116)

如何在2d numpy数组中找到包含数组范围最大值的行或列?

cl25kdpy

cl25kdpy1#

您可以将np.argmax沿着与np.unravel_index一起使用,如

x = np.random.random((5,5))
print np.unravel_index(np.argmax(x), x.shape)
dohp0rv5

dohp0rv52#

如果你只需要一个或另一个:

np.argmax(np.max(x, axis=1))

对于列,以及

np.argmax(np.max(x, axis=0))

为行。

toiithl6

toiithl63#

可以使用np.where(x == np.max(x))
举例来说:

>>> 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]))

第一个值是行号,第二个数字是列号。

nwwlzxa7

nwwlzxa74#

np.argmax只返回扁平数组中(第一个)最大元素的索引。所以如果你知道你的数组的形状(你确实知道),你可以很容易地找到行/列索引:

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]
xjreopfe

xjreopfe5#

可以直接使用np.argmax()
这个例子是从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是在每一列中找到最大值,而axis = 1是在每行中找到最大值。返回的是列/行索引。

相关问题