首页 > 解决方案 > 用数字序列填充 numpy 数组

问题描述

我有一个 numpy 数组,其形状(6, 3, 4)我想用数字的升序填充,因此结果数组是这样的:

array([[[0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]],

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

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

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

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

   [[5, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]]], dtype=uint8)

如果可能的话,我不想使用循环。

我试过以下没有运气:

import numpy as np

new_row = np.zeros([6, 3, 4], dtype=np.uint8)
new_row[:,0:1,0:1] = range(6)

这导致ValueError: could not broadcast input array from shape (6) into shape (6,1,1)

任何帮助表示赞赏

标签: pythonarraysnumpy

解决方案


推荐阅读