Replace auxiliary part of matrix with another small matrix in numpy

I am new to Numpy and want to replace part of the 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]])

In the end, I want to make A the next 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]])

and / or following

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 to follow, but it did not work. Now I do not know :(

A[[0,1],:][:,[3,4]] = B

or even i tried like

A[[0,1],:][:,[3,4]] = 1

to check if four cells are changed. Do you have any ideas?

+4
source share
2 answers

Here's how you can do it:

>>> 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]])
+3
source

For the first:

In [13]: A[-B.shape[0]:, -B.shape[1]:] = B                              

In [14]: A
Out[14]: 
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]])   

For the second:

In [15]: A = np.ones((5,5))                                             

In [16]: A[:B.shape[0], -B.shape[1]:] = B                               

In [17]: A
Out[17]: 
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. ]])   
+3
source

All Articles