138

我有一个二维 NumPy 数组。我知道如何获得轴上的最大值:

>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])

如何获得最大元素的索引?我想array([1,1,0])改为输出。

4

5 回答 5

170
>>> a.argmax(axis=0)

array([1, 1, 0])
于 2011-03-29T07:39:43.607 回答
114
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4
于 2012-11-23T20:52:54.133 回答
42

argmax()只会返回每行的第一次出现。 http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html

如果您需要对形状数组执行此操作,这比unravel

import numpy as np
a = np.array([[1,2,3], [4,3,1]])  # Can be of any shape
indices = np.where(a == a.max())

您还可以更改条件:

indices = np.where(a >= 1.5)

以上以您要求的形式为您提供结果。或者,您可以通过以下方式转换为 x,y 坐标列表:

x_y_coords =  zip(indices[0], indices[1])
于 2014-05-08T22:58:16.420 回答
3
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
于 2012-07-10T03:20:07.920 回答
2

There isargmin()argmax()provided bynumpy分别返回 numpy 数组的最小值和最大值的索引。

比如说一维数组,你会做这样的事情

import numpy as np

a = np.array([50,1,0,2])

print(a.argmax()) # returns 0
print(a.argmin()) # returns 2

同样对于多维数组

import numpy as np

a = np.array([[0,2,3],[4,30,1]])

print(a.argmax()) # returns 4
print(a.argmin()) # returns 0

请注意,这些只会返回第一次出现的索引。

于 2020-11-08T16:47:35.920 回答