我有一个二维 NumPy 数组。我知道如何获得轴上的最大值:
>>> a = array([[1,2,3],[4,3,1]])
>>> amax(a,axis=0)
array([4, 3, 3])
如何获取最大元素的索引?我想要作为输出
array([1,1,0])
。
>>> a.argmax(axis=0)
array([1, 1, 0])
>>> 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
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])
argmin()
提供了argmax()
和numpy
,分别返回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
请注意,这些只会返回第一次出现的索引。
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
请允许我给出最新的答案。
>>>import numpy as np
>>>a = np.array([[1,2,3],[4,3,1]])
>>>per_column = a.argmax(axis=0) #This will get the index of the max value for each column (this array has 3 columns)
>>>print(per_column)
[1 1 0]
>>>per_row = a.argmax(axis=1) #This will get the index of the max value for each row (this array has 3 rows)
print(per_row)
[2 0]