簡體   English   中英

將多維元素附加到numpy數組中,而無需重塑

[英]appending multidimensional elements into numpy arrays without reshaping

我有幾個簡單的問題,我找不到答案。 它們都在下面的示例代碼中說明。 感謝您的任何幫助!

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)) 

編輯:使代碼更簡單

要回答您的第一個問題,您可以使用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')))

迭代構建數組的正確方法是使用列表追加。 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)

最好完全避免循環,但是如果必須的話,請使用此列表追加方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM