Numpy 使用另一个3D索引数组为4D数组编制索引

Numpy 使用另一个3D索引数组为4D数组编制索引,numpy,matrix-indexing,Numpy,Matrix Indexing,A具有4D数组M(A x b x c x d)和索引数组I(3 x f),例如 我想使用I得到一个矩阵X,该矩阵有f行和d列,其中: X[0,:] = M[1,2,4,:] X[1,:] = M[2,1,1,:] X[2,:] = M[3,3,6,:] ... 我知道我可以使用M[I[0],I[1],I[2]],但是,我想知道是否有更简洁的解决方案?这是一种方法- import numpy as np # Get row indices for use when M is reshaped

A具有4D数组
M
A x b x c x d
)和索引数组
I
3 x f
),例如

我想使用
I
得到一个矩阵
X
,该矩阵有
f
行和
d
列,其中:

X[0,:] = M[1,2,4,:]
X[1,:] = M[2,1,1,:]
X[2,:] = M[3,3,6,:]
...

我知道我可以使用
M[I[0],I[1],I[2]]
,但是,我想知道是否有更简洁的解决方案?

这是一种方法-

import numpy as np

# Get row indices for use when M is reshaped to a 2D array of d-columns format
row_idx = np.sum(I*np.append(1,np.cumprod(M.shape[1:-1][::-1]))[::-1][:,None],0)

# Reshape M to d-columns 2D array and use row_idx to get final output
out = M.reshape(-1,M.shape[-1])[row_idx]
作为查找
row\u idx
的替代方法,如果您希望避免
np.append
,您可以这样做-

row_idx = np.sum(I[:-1]*np.cumprod(M.shape[1:-1][::-1])[::-1][:,None],0) + I[-1]
或者用不那么可怕的方式获得
行\u idx
-

_,p2,p3,_ = M.shape
row_idx = np.sum(I*np.array([p3*p2,p3,1])[:,None],0)

您可以使用,例如:

I = np.array([[1,2,3], [2,1,3], [4,1,6]])
M = np.ndarray((10,10,10,10))
X = np.array([M[t,:] for t in I])

您现有的解决方案看起来相当简洁,不是吗?
I = np.array([[1,2,3], [2,1,3], [4,1,6]])
M = np.ndarray((10,10,10,10))
X = np.array([M[t,:] for t in I])