Skip to main content
 首页 » 编程设计

python之在不 reshape 的情况下将多维元素 append 到 numpy 数组中

2025年05月04日25yjmyzz

我有几个简单的问题找不到答案。它们都在以下示例代码中说明。感谢您的任何帮助!

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 列输出数组,我们仍然需要重新整形。


我们可以通过其他方式构建具有网状结构的阵列,从而避免 reshape 。其中一种方法是使用 np.column_stack,如下所示 -

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