2012-12-21 252 views
22

我有這樣3D numpy的陣列到2d

arange(16).reshape((4,2,2)) 
array([[[ 0, 1], 
     [ 2, 3]], 

     [[ 4, 5], 
     [ 6, 7]], 

     [[ 8, 9], 
     [10, 11]], 

     [[12, 13], 
     [14, 15]]]) 

一個三維矩陣,並想將它們堆疊在網格格式,結束了

array([[ 0, 1, 4, 5], 
     [ 2, 3, 6, 7], 
     [ 8, 9, 12, 13], 
     [10, 11, 14, 15]]) 

有沒有明確這樣做的一種方式堆棧(和/或vstacking)他們或增加一個額外的維度和重塑(不知道這會工作)?

感謝,

+0

向我們顯示您的代碼。 – tostao

回答

35
In [27]: x = np.arange(16).reshape((4,2,2)) 

In [28]: x.reshape(2,2,2,2).swapaxes(1,2).reshape(4,-1) 
Out[28]: 
array([[ 0, 1, 4, 5], 
     [ 2, 3, 6, 7], 
     [ 8, 9, 12, 13], 
     [10, 11, 14, 15]]) 

我已經發布了更廣泛的功能reshaping/unshaping arrays into blocks, here

+15

對NumPy的這種掌握感到驚訝。 :) – EOL

+0

好的,所以考慮到我有N個塊矩陣和'bm x bn'維度並且想要將它們堆疊在一個'mxn'矩陣中,提供'N = mxn',那麼我就有了 'x.reshape(m, n,bm,bn).swapaxes(1,2).reshape(bm * m,-1)' 只是想知道是否有任何numpy函數用於此目的。再次感謝@unutbu。 – poeticcapybara

+1

@EOL:謝謝你,EOL,但是如果你看到[幕後發生了什麼](http://www.youtube.com/watch?v=sY_Yf4zz-yo),它不是那麼漂亮:) – unutbu