2017-07-26 202 views
2

假設我有一個形狀爲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

回答

4

看來您使用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]]) 
0

如果你的矩陣得到比3x3的大得多,到如此地步,存儲參與np.ogrid是一個問題,如果你的索引值的二進制文件,你也可以這樣做:

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

但除了那個角落案例(或者如果你喜歡代碼打高爾夫單線),其他答案可能會更好。