python - 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.]])
有谁知道如何做到这一点以及为什么我会收到上述错误?
解决方案
您可以插入一个二维数组,但您需要使用一个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)
。
推荐阅读
- linux - salt-minion 旧版本中不存在 http 代理设置
- apache-flink - 如何使用 Flink CEP 创建批处理或滑动窗口?
- angular - Jasmine 单元测试 HttpInterceptor 验证方法参数
- python - 在 Python 中使用二分法计算付款大小
- javascript - Angular 2 更改 ngFor 项目类只知道它的索引
- r - 通过复制 2 个元素创建数据框
- r - 在 R 中选择了未定义的列
- android - 改造从复杂的 JSON 响应中获取信息
- java - Mongo:“不允许等待复制”
- sitecore - 将 appsetting 添加到 helix 解决方案中的根 web.config 文件