2017-08-08 44 views
1

如何扁平化這樣的:拼合3 d numpy的陣列

b = np.array([ 
    [[1,2,3], [4,5,6], [7,8,9]], 
    [[1,1,1],[2,2,2],[3,3,3]] 
]) 

到:

c = np.array([ 
    [1,2,3,4,5,6,7,8,9], 
    [1,1,1,2,2,2,3,3,3] 
]) 

Niether這些工作:

c = np.apply_along_axis(np.ndarray.flatten, 0, b) 
c = np.apply_along_axis(np.ndarray.flatten, 0, b) 

剛剛返回相同的陣列。

這將是很好的扁平化這個地方。

回答

2

這將做的工作:

c=b.reshape(len(b),-1) 

然後c

array([[1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [1, 1, 1, 2, 2, 2, 3, 3, 3]]) 
+0

什麼'-1'確實在'reshape'? – dokondr

+1

這是自動計算該維度大小的快捷方式。由於'b.size = 18'和'len(b)= 2','-1'被計算爲'18/2 = 9' –

0

您可以完全壓平,然後重塑:

c = b.flatten().reshape(b.shape[0],b.shape[1]*b.shape[2]) 

輸出

array([[1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [1, 1, 1, 2, 2, 2, 3, 3, 3]]) 
0

所以,你總是可以只使用重塑:

b.reshape((2,9)) 
array([[1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [1, 1, 1, 2, 2, 2, 3, 3, 3]])