2

我有一个 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[:,:,:]。有什么好的方法吗?

4

2 回答 2

5

您可以从 (5,) 重塑s为 (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]]])
于 2013-09-12T12:20:25.887 回答
0
tmp = C.swapaxes(1, 2)
tmp[:] = s
C = tmp.swapaxes(1, 2)
于 2013-09-12T12:06:58.343 回答