Python: Resize an existing array and fill with zeros

后端 未结 5 1379
遥遥无期
遥遥无期 2020-12-30 20:55

I think that my issue should be really simple, yet I can not find any help on the Internet whatsoever. I am very new to Python, so it is possible that I am missing somethin

5条回答
  •  甜味超标
    2020-12-30 21:43

    There is a new numpy function in version 1.7.0 numpy.pad that can do this in one-line. Like the other answers, you can construct the diagonal matrix with np.diag before the padding. The tuple ((0,N),(0,0)) used in this answer indicates the "side" of the matrix which to pad.

    import numpy as np
    
    A = np.array([1, 2, 3])
    
    N = A.size
    B = np.pad(np.diag(A), ((0,N),(0,0)), mode='constant')
    

    B is now equal to:

    [[1 0 0]
     [0 2 0]
     [0 0 3]
     [0 0 0]
     [0 0 0]
     [0 0 0]]
    

提交回复
热议问题