Replace sub part of matrix by another small matrix in numpy

后端 未结 4 879
借酒劲吻你
借酒劲吻你 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条回答
  •  一整个雨季
    2020-12-03 21:31

    In general, for example, for non-contiguous rows/cols use numpy.putmask(a, mask, values) (Sets a.flat[n] = values[n] for each n where mask.flat[n]==True)

    For example

    In [1]: a = np.zeros((3, 3))
    Out [1]: a
    array([[0., 0., 0.],
           [0., 0., 0.],
           [0., 0., 0.]])
    
    In [2]: values = np.ones((2, 2))
    Out [2]: values
    array([[1., 1.],
           [1., 1.]])
    
    In [3]: mask = np.zeros((3, 3), dtype=bool)
    In [4]: mask[0,0] = mask[0,1] = mask[1,1] = mask[2,2] = True
    
    Out [4]: mask
    array([[ True,  True, False],
           [False,  True, False],
           [False, False,  True]])
    
    In [5] np.putmask(a, mask, values)
    Out [5] a
    array([[1., 1., 0.],
           [0., 1., 0.],
           [0., 0., 1.]])
    

提交回复
热议问题