首页 > 解决方案 > Numpy Python - 在 numpy 矩阵的索引列表中插入矩阵

问题描述

我正在尝试在 Numpy 矩阵的多个索引处插入多列。

到目前为止,我有以下代码:

MatrixA = np.zeros(shape=(200,300))
MatrixB = np.ones(shape=(200,1))
index_list = [1,3,5]
Output = np.insert(MatrixA, index_list, MatrixB, axis=1)

它返回类似于我正在寻找的输出:

array([[0., 1., 0., 1., ..., 0., 0., 0.],
       [0., 1., 0., 1., ..., 0., 0., 0.],
       [0., 1., 0., 1., ..., 0., 0., 0.],
       ...,
       [0., 1., 0., 1., ..., 0., 0., 0.],
       [0., 1., 0., 1., ..., 0., 0., 0.],
       [0., 1., 0., 1., ..., 0., 0., 0.]])

但是,这仅适用于单个列。当我尝试添加多个列时:

MatrixA = np.zeros(shape=(200,300))
MatrixB = np.ones(shape=(200,2))
index_list = [1,3,5]
Output = np.insert(MatrixA, index_list, MatrixB, axis=1)

我收到一个错误:

ValueError:形状不匹配:形状(200,2)的值数组无法广播到形状(3,200)的索引结果

我想要的输出是这样的:

array([[0., 1., 1., 0., 1., 1., ..., 0., 0., 0.],
       [0., 1., 1., 0., 1., 1., ..., 0., 0., 0.],
       [0., 1., 1., 0., 1., 1., ..., 0., 0., 0.],
       ...,
       [0., 1., 1., 0., 1., 1., ..., 0., 0., 0.],
       [0., 1., 1., 0., 1., 1., ..., 0., 0., 0.],
       [0., 1., 1., 0., 1., 1., ..., 0., 0., 0.]])

有谁知道如何做到这一点以及为什么我会收到上述错误?

标签: pythonnumpy

解决方案


您可以插入一个二维数组,但您需要使用一个slice对象。我无法一次将多个切片传递给np.insert,因此,如果计算要求不高,您可以执行 for 循环,即:

slices = [slice(i, i+MatrixB.shape[1]) for i in index_list]

for s in slices:
     MatrixA[:,s] = MatrixB

请注意,这等同于np.insert,因为它不会为 增加维度MatrixA。计算后,MatrixA.shape仍为(200,300)


推荐阅读