2015-01-05 140 views
1

我有一個numpy的陣列稱爲這是這樣如何分割/重塑numpy的陣列

array([1, 2, 3, 4, 5, 6]) 

定義的「結果」,但我需要它看起來像這樣:

array([1, 2], [3, 4], [5, 6]) 

哪有我將'結果'轉換爲Python中的這個新數組?我最後得到的數組仍然需要是一個numpy數組。

+0

你期望的結果是不可能的,你缺少的外部列表:'陣列([1,2],[3 ,4],[5,6]])'。 – sebix

回答

5

您可以通過使用reshape方法直接實現此目的。

例如:

In [1]: import numpy as np 

In [2]: arr = np.array([1, 2, 3, 4, 5, 6]) 

In [3]: reshaped = arr.reshape((3, 2)) 

In [4]: reshaped 
Out[4]: 
array([[1, 2], 
     [3, 4], 
     [5, 6]]) 

注意,如果可能的話,reshape會給你的陣列的視圖。換句話說,您正在查看與原始數組相同的底層數據:

In [5]: reshaped[0][0] = 7 

In [6]: reshaped 
Out[6]: 
array([[7, 2], 
     [3, 4], 
     [5, 6]]) 

In [7]: arr 
Out[7]: array([7, 2, 3, 4, 5, 6]) 

這幾乎總是一個優勢。但是,如果你不希望這種行爲,你總是可以採取一個副本:

In [8]: copy = np.copy(reshaped) 

In [9]: copy[0][0] = 9 

In [10]: copy 
Out[10]: 
array([[9, 2], 
     [3, 4], 
     [5, 6]]) 

In [11]: reshaped 
Out[11]: 
array([[7, 2], 
     [3, 4], 
     [5, 6]]) 
+0

謝謝你,我工作。 – sdsnaught