分配给多维数组

时间:2013-09-12 12:00:13

标签: python arrays numpy

我有一个零的3d数组,我想用1d数组填充它:

In [136]: C = np.zeros((3,5,6),dtype=int)

In [137]: C
Out[137]: 
array([[[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]]])

In [138]: s
Out[138]: array([10, 20, 30, 40, 50])

我想实现这个目标:(不使用循环)

array([[[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]],

       [[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]],

       [[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]]])

通过将s分配给每个第i个元素的每一列。

注意我可以很容易地得到类似的东西:

array([[[10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60]],

       [[10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60]],

       [[10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60],
        [10, 20, 30, 40, 50, 60]]])

通过:

 C[:,:,:] = s

但是看不出如何在[i,j,k]中为所有i和k分配s到j

似乎numpy优先考虑最后一个冒号C [:,:,]。这有什么好办法吗?

2 个答案:

答案 0 :(得分:5)

您可以将s从(5,)转换为(5,1):

>>> C[:] = s.reshape(5,1)
>>> C
array([[[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]],

       [[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]],

       [[10, 10, 10, 10, 10, 10],
        [20, 20, 20, 20, 20, 20],
        [30, 30, 30, 30, 30, 30],
        [40, 40, 40, 40, 40, 40],
        [50, 50, 50, 50, 50, 50]]])

答案 1 :(得分:0)

tmp = C.swapaxes(1, 2)
tmp[:] = s
C = tmp.swapaxes(1, 2)