简体   繁体   English

将多维元素附加到numpy数组中,而无需重塑

[英]appending multidimensional elements into numpy arrays without reshaping

I have a few simple questions I'm not able to find the answer to. 我有几个简单的问题,我找不到答案。 They are both stated in the following example code. 它们都在下面的示例代码中说明。 Thank you for any help! 感谢您的任何帮助!

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

edit: made code more minimal 编辑:使代码更简单

To answer your first question, you can use np.meshgrid to form those combinations between elements of the two input arrays and get to the final version of temp in a vectorized manner avoiding those loops, like so - 要回答您的第一个问题,您可以使用np.meshgrid在两个输入数组的元素之间形成那些组合,并以向量化的方式获得temp的最终版本,从而避免这些循环,如下所示-

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

As seen, we would still need a reshape if you intend to get a 2-column output array. 如所看到的,如果您打算获得2列输出数组,我们仍然需要重塑形状。


There are other ways we could construct the array with the meshed structure and thus avoid a reshape. 我们还有其他方法可以使用网状结构构造数组,从而避免重塑形状。 One of those ways would be with np.column_stack , as shown below - 其中一种方法是使用np.column_stack ,如下所示-

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

The proper way to build an array iteratively is with list append. 迭代构建数组的正确方法是使用列表追加。 np.append is poorly named, and often mis used. 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)

It's better to avoid loops at all, but if you must, use this list append approach. 最好完全避免循环,但是如果必须的话,请使用此列表追加方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM