简体   繁体   English

将向量排列成矩阵的向量化方式(numpy)

[英]Vectorized way to arrange vector into matrix (numpy)

I have 4 vectors of the same dimentions (say 3) 我有4个相同维数的向量(例如3)

a= [1, 5, 9]
b= [2, 6, 10]
c= [3, 7, 11]
d= [4, 8, 12]

What i want to do with numpy is to create a matrix of dimensions 3x2x2 that has this structure 我想用numpy做的是创建一个具有这种结构的尺寸为3x2x2的矩阵

在此处输入图片说明

so the resultan matrices will be like this 所以结果矩阵将是这样的

[
[[1, 2],[3,4]],
[[5, 6],[7,8]],
[[9, 10],[11,12]],
]

I know that it is pretty easy using a for loop but I'm looking for a vectorized approach. 我知道使用for循环非常容易,但是我正在寻找一种向量化方法。

Thanks in advance 提前致谢

np.stack is handy tool for combining arrays (or in this case lists) in various orders: np.stack是用于以各种顺序组合数组(或本例中的列表)的便捷工具:

In [74]: a= [1, 5, 9]
    ...: b= [2, 6, 10]
    ...: c= [3, 7, 11]
    ...: d= [4, 8, 12]
    ...: 
    ...:

Default without axis parameter is like np.array , adding a new initial dimension: 没有轴参数的默认值类似于np.array ,添加一个新的初始尺寸:

In [75]: np.stack((a,b,c,d))
Out[75]: 
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])

But the order isn't what you want. 但是订单不是您想要的。 Lets try axis=1 : 让我们尝试axis=1

In [76]: np.stack((a,b,c,d),1)
Out[76]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Order looks right. 订单看起来正确。 Now add a reshape: 现在添加一个重塑:

In [77]: np.stack((a,b,c,d),1).reshape(3,2,2)
Out[77]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]]])

Another approach is to join the lists, reshape and transpose: 另一种方法是加入列表,重塑和转置:

In [78]: np.array([a,b,c,d])
Out[78]: 
array([[ 1,  5,  9],
       [ 2,  6, 10],
       [ 3,  7, 11],
       [ 4,  8, 12]])
In [79]: _.reshape(2,2,3)
Out[79]: 
array([[[ 1,  5,  9],
        [ 2,  6, 10]],

       [[ 3,  7, 11],
        [ 4,  8, 12]]])
In [80]: _.transpose(2,1,0)
Out[80]: 
array([[[ 1,  3],
        [ 2,  4]],

       [[ 5,  7],
        [ 6,  8]],

       [[ 9, 11],
        [10, 12]]])
In [81]: __.transpose(2,0,1)
Out[81]: 
array([[[ 1,  2],
        [ 3,  4]],

       [[ 5,  6],
        [ 7,  8]],

       [[ 9, 10],
        [11, 12]]])

We can try to be systematic about this, but I find it instructive to experiment, trying various alternatives. 我们可以尝试对此进行系统化,但是我发现尝试各种替代方法很有帮助。

np.reshape() will do it: np.reshape()可以做到:

np.reshape(np.array([a,b,c,d]).T,[3,2,2])

will produce the desired result. 将产生期望的结果。

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

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