2010-12-03 227 views
5

我有一個數百個10x10陣列的列表,我想將它們堆疊到一個Nx10x10陣列中。起初,我嘗試了簡單的將2D numpy數組列表轉換爲一個3D numpy數組?

newarray = np.array(mylist)

但與返回「ValueError異常:設置一個數組元素與序列」

然後我發現對於dstack)的在線文檔(,看上去完美:「...這是堆疊二維數組(圖像)轉換成用於處理的單個3D陣列的簡單方法。」這正是我想要做的。然而,

newarray = np.dstack(mylist) 

告訴我:因爲我所有的數組是10×10這是奇怪的「ValueError異常陣列的尺寸必須除D_0同意」。我想也許問題是dstack()期望一個元組而不是一個列表,但是

newarray = np.dstack(tuple(mylist)) 

產生了相同的結果。

在這一點上我花了約兩個小時的搜索在這裏和其他地方,找出我在做什麼錯誤和/或如何去正確此。我甚至試圖將我的數組列表轉換爲列表列表,然後返回到3D數組中,但這也不起作用(我最終列出了數組列表,然後是「設置數組元素作爲序列「錯誤再次)。

任何幫助,將不勝感激。

+1

當你做類似`[item.shape for item in item,item item = [(10,10)]``時,你會得到什麼? (即是你_really_確保所有的陣列具有相同的形狀?) – 2010-12-03 05:13:01

+1

dstack你去哪兒了我所有的生活..我一直在使用hstack和vstack與[:,:,newaxis]垃圾 – wim 2011-05-29 03:32:59

回答

13
newarray = np.dstack(mylist) 

應該工作。例如:

import numpy as np 

# Here is a list of five 10x10 arrays: 
x=[np.random.random((10,10)) for _ in range(5)] 

y=np.dstack(x) 
print(y.shape) 
# (10, 10, 5) 

# To get the shape to be Nx10x10, you could use rollaxis: 
y=np.rollaxis(y,-1) 
print(y.shape) 
# (5, 10, 10)