简体   繁体   English

从Numpy中的2个向量形成矩阵,重复1个向量

[英]Forming matrix from 2 vectors in Numpy, with repetition of 1 vector

Using numpy arrays I want to create such a matrix most economically: given 使用numpy数组我想以最经济的方式创建这样一个矩阵:给定

from numpy import array
a = array(a1,a2,a3,...,an)
b = array(b1,...,bm)

shall be processed to matrix M: 应处理为矩阵M:

M = array([[a1,a2,b1,...,an],
           ...           ...,
           [a1,a2,bm,...,an]]

I am aware of numpy array's broadcasting methods but couldn't figure out a good way. 我知道numpy数组的广播方法,但无法找到一个好方法。 Any help would be much appreciated, 任何帮助将非常感激,

cheers, Rob 欢呼,罗布

You can use numpy.resize on a first and then add b 's items at the required indices using numpy.insert on the re-sized array: 您可以使用numpy.resizea ,然后再加入b在使用所需的指标的项目numpy.insert重新大小的阵列上:

In [101]: a = np.arange(1, 4)

In [102]: b = np.arange(4, 6)                                           

In [103]: np.insert(np.resize(a, (b.shape[0], a.shape[0])), 2, b, axis=1)                                                                       
Out[103]: 
array([[1, 2, 4, 3],                                                    
       [1, 2, 5, 3]])  

You can use a combination of numpy.tile and numpy.hstack functions. 您可以使用numpy.tilenumpy.hstack函数的组合。

M = numpy.repeat(numpy.hstack(a, b), (N,1))

I'm not sure I understand your target matrix, though. 不过,我不确定我是否理解你的目标矩阵。

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

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