Replace sub part of matrix by another small matrix in numpy

后端 未结 4 885
借酒劲吻你
借酒劲吻你 2020-12-03 21:05

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[         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 21:24

    For the first one:

    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 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. ]])   
    

提交回复
热议问题