使用2D矩阵作为numpy 3D矩阵的索引?

问题描述:

假设我有一个形状为2x3x3的阵列,这是一个3D矩阵。我还有一个形状为3x3的2D矩阵,我想用它作为沿第一轴的3D矩阵的索引。示例如下。使用2D矩阵作为numpy 3D矩阵的索引?

实施例运行:

>>> np.random.randint(0,2,(3,3)) # index 
array([[0, 1, 0], 
     [1, 0, 1], 
     [1, 0, 0]]) 

>> np.random.randint(0,9,(2,3,3)) # 3D matrix 
array([[[4, 4, 5], 
     [2, 6, 7], 
     [2, 6, 2]], 

     [[4, 0, 0], 
     [2, 7, 4], 
     [4, 4, 0]]]) 
>>> np.array([[4,0,5],[2,6,4],[4,6,2]]) # result 
array([[4, 0, 5], 
     [2, 6, 4], 
     [4, 6, 2]]) 
+0

二维数组的形状与三维数组的形状有什么关系? – Divakar

+0

它具有相同的2D形状,但只有2D。所以3D阵列与2D阵列具有相同的形状NxN,但具有更多“层”。 –

+0

你的2个不同的矩阵像例子那样重复数字吗?否则,您需要提供更多关于您希望输出结果的信息。例如,0和1对你意味着什么? – Flynn

看来您使用2D数组作为索引阵列和3D阵列来选择值。因此,你可以使用与NumPy的advanced-indexing -

# a : 2D array of indices, b : 3D array from where values are to be picked up 
m,n = a.shape 
I,J = np.ogrid[:m,:n] 
out = b[a, I, J] # or b[a, np.arange(m)[:,None],np.arange(n)] 

如果你想用a索引到最后反而轴,只需移动a有:b[I, J, a]

采样运行 -

>>> np.random.seed(1234) 
>>> a = np.random.randint(0,2,(3,3)) 
>>> b = np.random.randint(11,99,(2,3,3)) 
>>> a # Index array 
array([[1, 1, 0], 
     [1, 0, 0], 
     [0, 1, 1]]) 
>>> b # values array 
array([[[60, 34, 37], 
     [41, 54, 41], 
     [37, 69, 80]], 

     [[91, 84, 58], 
     [61, 87, 48], 
     [45, 49, 78]]]) 
>>> m,n = a.shape 
>>> I,J = np.ogrid[:m,:n] 
>>> out = b[a, I, J] 
>>> out 
array([[91, 84, 37], 
     [61, 54, 41], 
     [37, 49, 78]]) 

如果你的矩阵得到比3x3的大得多,到如此地步,存储参与np.ogrid是一个问题,如果你的索引值的二进制文件,你也可以这样做:

np.where(a, b[1], b[0]) 

但除了那个角落案例(或者如果你喜欢代码打高尔夫单线),其他答案可能会更好。