2016-07-16 160 views
-3

我如何索引在拆分numpy的陣列拆分numpy的陣列

import numpy as np 
a = np.random.random((3,3,3)) 
#What i want to achieve is 3 x (3x3) matrix 

我想我(3,3,3)矩陣轉換成(3×3)矩陣列表

我可以這樣做:

b = [] 
for i in a: 
    b.append(i) 

但應該有更好的方式

+0

我不明白是什麼問題:'一[0]','一[1]'和'a [2]'是3x3。 –

+0

我可以做一個for循環,並追加每個[0],a [1],a [2]列表,但我想知道是否有更好的方式 – aceminer

回答

3

爲了清楚要一個3維陣列轉換成包含三個2維陣列列表。

您可以直接分配陣列,以新的名稱(其中3):

import numpy as np 

a = np.random.random((3,3,3)) 
b,c,d = a 
my_list = [b, c, d] 

你有新的陣列和結果列表。

如果不需要數組,那麼你可以使用numpy的數組tolist方法:

my_list = a.tolist() 
-1

更Python的方式是使用列表理解:

b = [x for x in a] 
+0

任何numpyic的方式?或jsut這將做 – aceminer

+2

「numpyic」的方式將保持它爲3x3x3 ... –

0

list可以採取任何可迭代的,所以你可以只使用它:

>>> import numpy as np 

>>> array = np.ones((3,3,3)) 
>>> list_of_arrays = list(array) # convert it to a list 

>>> list_of_arrays 
[array([[ 1., 1., 1.], 
     [ 1., 1., 1.], 
     [ 1., 1., 1.]]), array([[ 1., 1., 1.], 
     [ 1., 1., 1.], 
     [ 1., 1., 1.]]), array([[ 1., 1., 1.], 
     [ 1., 1., 1.], 
     [ 1., 1., 1.]])] 

然而,有(幾乎)沒有任何理由將你的numpy數組轉換爲數組列表。如果您只想訪問陣列的某些元素,則有slicing and indexing。如果您需要類似表格的數組,則有structured arraysPandas Dataframe。此外,它總是可以使用axis參數爲numpy的功能,他們對你的3x3矩陣一氣呵成適用於:

>>> array = np.ones((3,3,3)) * np.array([1,2,3]).reshape(3,1,1) 

>>> array.sum(axis=(1,2)) # getting the sum of all the 3x3 matrices 
array([ 9., 18., 27.])