2017-04-01 55 views
2

我想重新塑造Numpy數組A,而不是通過追加正常的下一行,而是追加它後面的每第N行。Numpy重新排序,使得當前行的每第n行都附加到它

例:

A = [[1 2 3 4] 
[5 6 7 8] 
[9 10 11 12] 
[13 14 15 16] 
[17 18 19 20] 
[21 22 23 24]] 

現在,我想從一個

A = [[1 2 3 4 9 10 11 12 17 18 19 10] 
[5 6 7 8 13 14 15 16 21 22 23 24]] 

建設規模2×12的陣列像這樣在這裏你可以看到,從當前行的每2行追加到它並形成了新的重塑陣列。

+0

或者:'A.reshape(-1,2,4).swapaxes(0,1).reshape(2,-1)' –

回答

2

您可以使用一個簡單的索引,array.ravel()np.vstack()

In [37]: np.vstack((A[::2].ravel(), A[1::2].ravel())) 
Out[37]: 
array([[ 1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20], 
     [ 5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24]]) 
+0

可你讓我明白了什麼[Rü做什麼? –

+0

@SurviMakharia如果你知道[numpy索引](https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html),你知道索引符號的第一部分表示開始,第二部分是停止,第三部分是步驟。其中'[1 :: 2]'表示從索引1開始,步驟2關於其他功能,您可以閱讀文檔。 – Kasramvd

2

這個怎麼樣的做法?

# extract alternative rows starting from 0th row (1st row) 
In [18]: A[0::2] 
Out[18]: 
array([[ 1, 2, 3, 4], 
     [ 9, 10, 11, 12], 
     [17, 18, 19, 20]]) 

# and then flatten to 1D array 
In [19]: A[0::2].flatten() 
Out[19]: array([ 1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20]) 


# extract alternative rows starting from 2nd row 
In [17]: A[1::2] 
Out[17]: 
array([[ 5, 6, 7, 8], 
     [13, 14, 15, 16], 
     [21, 22, 23, 24]]) 


# and then flatten to 1D array 
In [20]: A[1::2].flatten() 
Out[20]: array([ 5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24]) 


# to get 2D, just put them in `np.vstack` (in the order you want the final array) 
In [21]: np.vstack((A[0::2].flatten(), A[1::2].flatten())) 
Out[21]: 
array([[ 1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20], 
     [ 5, 6, 7, 8, 13, 14, 15, 16, 21, 22, 23, 24]])