我不知道这是否简单,或者是否曾被问过。 (我进行了搜索,但没有找到正确的方法。我找到了numpy.argmax
和numpy.amax
,但无法正确使用它们。)
我有一个如下的numpy数组(它是CxKxN
矩阵)(C=K=N=3
):
array([[[1, 2, 3],
[2, 1, 4],
[4, 3, 3]],
[[2, 1, 1],
[1, 3, 1],
[3, 4, 2]],
[[5, 2, 1],
[3, 3, 3],
[4, 1, 2]]])
我想找到每一行中最大元素的索引。一行是每个矩阵的三(C
)行的串联。换句话说,第i
行是第一个矩阵中的第i
行,第二矩阵中的第i
行的串联,直到第i
矩阵中的第C
行。
例如,第一行是
[1, 2, 3, 2, 1, 1, 5, 2, 1]
所以我想返回
[2, 0, 0] # the index of the maximum in the first line
和
[0, 1, 2] # the index of the maximum in the second line
和
[0, 2, 0] # the index of the maximum in the third line
或
[1, 2, 1] # the index of the maximum in the third line
或
[2, 2, 0] # the index of the maximum in the third line
现在,我正在尝试
np.argmax(a[:,0,:], axis=None) # for the first line
它返回6
和
np.argmax(a[:,1,:], axis=None)
并返回2
和
np.argmax(a[:,2,:], axis=None)
并返回0
但是我能够将这些数字转换为6 = (2,0,0)
等索引。
答案 0 :(得分:1)
通过移调和整形,我得到了“行”
In [367]: arr.transpose(1,0,2).reshape(3,9)
Out[367]:
array([[1, 2, 3, 2, 1, 1, 5, 2, 1],
[2, 1, 4, 1, 3, 1, 3, 3, 3],
[4, 3, 3, 3, 4, 2, 4, 1, 2]])
In [368]: np.argmax(_, axis=1)
Out[368]: array([6, 2, 0])
这些最大值与您的最大值相同。相同的索引,但在(3,3)数组中:
In [372]: np.unravel_index([6,2,0],(3,3))
Out[372]: (array([2, 0, 0]), array([0, 2, 0]))
以中等尺寸范围加入它们:
In [373]: tup = (_[0],np.arange(3),_[1])
In [374]: np.transpose(tup)
Out[374]:
array([[2, 0, 0],
[0, 1, 2],
[0, 2, 0]])