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