Numpy 多维数组上的np.argmax,保持某些索引固定

Numpy 多维数组上的np.argmax,保持某些索引固定,numpy,multidimensional-array,indexing,argmax,Numpy,Multidimensional Array,Indexing,Argmax,我有一个2D光线的集合,取决于两个整数索引,比如p1和p2,每个矩阵的形状都相同 然后我需要找到,对于每一对(p1,p2),矩阵的最大值和这些最大值的索引。 一个简单但缓慢的方法是这样做 import numpy as np import itertools range1=range(1,10) range2=range(1,20) for p1,p2 in itertools.product(range1,range1): mat=np.random.rand(10,10)

我有一个2D光线的集合,取决于两个整数索引,比如p1和p2,每个矩阵的形状都相同

然后我需要找到,对于每一对(p1,p2),矩阵的最大值和这些最大值的索引。 一个简单但缓慢的方法是这样做

import numpy as np
import itertools
range1=range(1,10)
range2=range(1,20)

for p1,p2 in itertools.product(range1,range1):
    mat=np.random.rand(10,10)
    index=np.unravel_index(mat.argmax(), mat.shape)
    m=mat[index]
    print m, index
不幸的是,对于我的应用程序来说,这太慢了,我想这是因为使用了double For循环。 因此,我尝试将所有内容打包到一个四维数组中(比如BigMatrix),其中前两个坐标是索引p1、p2,另外两个是矩阵的坐标

np.amax命令

    >>res=np.amax(BigMatrix,axis=(2,3))
    >>res.shape
         (10,20)
    >>res[p1,p2]==np.amax(BigMatrix[p1,p2,:,:])
         True
按预期工作,因为它在2轴和3轴上循环。如何对np.argmax执行相同的操作?请记住速度很重要

事先非常感谢


Enzo

这对我来说很有用,
Mat
是一个大矩阵

# flatten the 3 and 4 dimensions of Mat and obtain the 1d index for the maximum
# for each p1 and p2
index1d = np.argmax(Mat.reshape(Mat.shape[0],Mat.shape[1],-1),axis=2)

# compute the indices of the 3 and 4 dimensionality for all p1 and p2
index_x, index_y = np.unravel_index(index1d,Mat[0,0].shape)

# bring the indices into the right shape
index = np.array((index_x,index_y)).reshape(2,-1).transpose()

# get the maxima
max_val = np.amax(Mat,axis=(2,3)).reshape(-1)

# combine maxima and indices
sol = np.column_stack((max_val,index))

print sol

非常感谢,这是快速和正确的。我应该更深入地研究numpy中的索引问题。