1

I'm having an issue with broadcasting. I want to be able to assign elements from 4 different arrays of shape x, y to 2x2 matrices without a for loop if possible.

a = np.arange(6).reshape(2,3)
b = np.arange(6,12).reshape(2,3)
c = np.arange(12,18).reshape(2,3)
d = np.arange(18,24).reshape(2,3)
x = np.array([[a, b], [c, d]])

obviously this doesn't work but I'd like x to come out an array of:

[   [
    [[0,6], [12, 18]], 
    [[1, 7], [13, 19]],
    [[2, 8], [14, 20]], 
    ],

    [
    [[3, 9], [15, 21]],
    [[4, 10], [16, 22]],
    [[5, 11], [17, 23]]
    ]
]
4

3 回答 3

2

这是一种方法np.dstackreshaping-

np.dstack((a,b,c,d)).reshape(a.shape + (2,2,))

样品运行 -

输入 :

In [32]: a
Out[32]: 
array([[0, 1, 2],
       [3, 4, 5]])

In [33]: b
Out[33]: 
array([[ 6,  7,  8],
       [ 9, 10, 11]])

In [34]: c
Out[34]: 
array([[12, 13, 14],
       [15, 16, 17]])

In [35]: d
Out[35]: 
array([[18, 19, 20],
       [21, 22, 23]])

输出 :

In [36]: np.dstack((a,b,c,d)).reshape(a.shape + (2,2,))
Out[36]: 
array([[[[ 0,  6],
         [12, 18]],

        [[ 1,  7],
         [13, 19]],

        [[ 2,  8],
         [14, 20]]],


       [[[ 3,  9],
         [15, 21]],

        [[ 4, 10],
         [16, 22]],

        [[ 5, 11],
         [17, 23]]]])
于 2016-01-15T16:56:34.427 回答
1

最简单的方法:x =np.array([[a, b], [c, d]]) 定义 后y=np.rollaxis(np.rollaxis(x,-1),-1)。这是一个关于 x 的视图,所以没有复制。

另一种方法:创建自己的新维度:

ac =np.concatenate((a[:,:,np.newaxis],c[:,:,np.newaxis]),axis=-1)
bd =np.concatenate((b[:,:,np.newaxis],d[:,:,np.newaxis]),axis=-1)
abcd =np.concatenate((ac[:,:,:,np.newaxis],bd[:,:,:,np.newaxis]),axis=-1)

然后

In [3]: abcd
Out[3]: array([[[[ 0,  6],
     [12, 18]],

    [[ 1,  7],
     [13, 19]],

    [[ 2,  8],
     [14, 20]]],


   [[[ 3,  9],
     [15, 21]],

    [[ 4, 10],
     [16, 22]],

    [[ 5, 11],
     [17, 23]]]])
于 2016-01-15T16:37:50.383 回答
1

这似乎是一个极端情况,最好的办法是构建数组,然后手动填充它:

a = np.arange(6).reshape(2,3)
b = np.arange(6,12).reshape(2,3)
c = np.arange(12,18).reshape(2,3)
d = np.arange(18,24).reshape(2,3)

out = np.zeros(a.shape + (2,2))
out[..., 0, 0] = a
out[..., 0, 1] = b
out[..., 1, 0] = c
out[..., 1, 1] = d

>>> out
array([[[[  0.,   6.],
         [ 12.,  18.]],

        [[  1.,   7.],
         [ 13.,  19.]],

        [[  2.,   8.],
         [ 14.,  20.]]],


       [[[  3.,   9.],
         [ 15.,  21.]],

        [[  4.,  10.],
         [ 16.,  22.]],

        [[  5.,  11.],
         [ 17.,  23.]]]])
于 2016-01-15T16:55:20.323 回答