本文介绍了用numpy中的另一个小矩阵替换矩阵的子部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Numpy的新手,想替换矩阵的一部分.例如,我有两个由numpy生成的矩阵A,B
I am new to Numpy and want to replace part of a matrix. For example, I have two matrices, A, B generated by numpy
In [333]: A = ones((5,5))
In [334]: A
Out[334]:
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
In [335]: B
Out[335]:
array([[ 0.1, 0.2],
[ 0.3, 0.4]])
最终,我想使A为以下矩阵.
Eventually, I want to make A be the following matrix.
In [336]: A
Out[336]:
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 0.1, 0.2],
[ 1., 1., 1., 0.3, 0.4]])
和/或以下
In [336]: A
Out[336]:
array([[ 1., 1., 1., 0.1, 0.2],
[ 1., 1., 1., 0.3, 0.4],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
我尝试按照以下步骤操作,但没有成功.我现在不知道:(
I tried like following but it didn't work. I don't have any idea now :(
A[[0,1],:][:,[3,4]] = B
甚至我尝试过
A[[0,1],:][:,[3,4]] = 1
检查是否更改了四个单元格.你有什么主意吗?
to check whether the four cell are changed or not. Do you have any idea?
推荐答案
以下是您的操作方法:
>>> A[3:5, 3:5] = B
>>> A
array([[ 1. , 1. , 1. , 1. , 1. ],
[ 1. , 1. , 1. , 1. , 1. ],
[ 1. , 1. , 1. , 1. , 1. ],
[ 1. , 1. , 1. , 0.1, 0.2],
[ 1. , 1. , 1. , 0.3, 0.4]])
这篇关于用numpy中的另一个小矩阵替换矩阵的子部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!