2017-03-14 43 views
1

我有幾個簡單的問題,我無法找到答案。它們都在以下示例代碼中聲明。感謝您的任何幫助!將多維元素添加到numpy數組中而無需重新塑形

import numpy as np 
#here are two arrays to join together 
a = np.array([1,2,3,4,5]) 
b = np.array([6,7,8,9,10]) 
#here comes the joining step I don't know how to do better 

#QUESTION 1: How to form all permutations of two 1D arrays? 

temp = np.array([]) #empty array to be filled with values 
for aa in a: 
    for bb in b: 
     temp = np.append(temp,[aa,bb]) #fill the array 

#QUESTION 2: Why do I have to reshape? How can I avoid this? 

temp = temp.reshape((int(temp.size/2),2)) 

編輯:由代碼的最小

+0

那麼,你的loopy部分是不是實現了形成所有排列的目標? – Divakar

+0

是的,但肯定有一個乾淨的方法來做到這一點?我試圖避免在numpy中循環數組。是否有一些像np.zip()我可以使用的應用程序? – kevinkayaks

回答

1

反覆地創建數組正確的方法是用列表追加。 np.append的名字很差,經常被誤用。

In [274]: a = np.array([1,2,3,4,5]) 
    ...: b = np.array([6,7,8,9,10]) 
    ...: 
In [275]: temp = [] 
In [276]: for aa in a: 
    ...:  for bb in b: 
    ...:   temp.append([aa,bb]) 
    ...:   
In [277]: temp 
Out[277]: 
[[1, 6], 
[1, 7], 
[1, 8], 
[1, 9], 
[1, 10], 
[2, 6], 
    .... 
[5, 9], 
[5, 10]] 
In [278]: np.array(temp).shape 
Out[278]: (25, 2) 

最好避免循環,但是如果你必須使用這個列表追加方法。

4

要回答你的第一個問題,你可以使用np.meshgrid形成兩個輸入數組的元素之間的組合,並獲取到的temp最終版本的量化方式避免這些循環,像這樣 -

np.array(np.meshgrid(a,b)).transpose(2,1,0).reshape(-1,2) 

如上所示,如果您打算獲得2列輸出數組,我們仍然需要重塑。


還有其他方法可以構造網格結構的陣列,從而避免重塑。其中的一個方法是用np.column_stack,如下圖所示 -

r,c = np.meshgrid(a,b) 
temp = np.column_stack((r.ravel('F'), c.ravel('F'))) 
+0

謝謝Divakar--我編輯了示例代碼,但現在應該是 np.array(np.meshgrid(a,b))。轉置(2,1,0).reshape(-1,2) – kevinkayaks

+0

@ kevinkayaks欣賞清理!相應地編輯我的代碼。 – Divakar