What's the simplest way to extend a numpy array in 2 dimensions?

前端 未结 7 993
后悔当初
后悔当初 2020-12-02 13:00

I have a 2d array that looks like this:

XX
xx

What\'s the most efficient way to add an extra row and column:

xxy
xxy
yyy
         


        
7条回答
  •  暖寄归人
    2020-12-02 13:48

    I find it much easier to "extend" via assigning in a bigger matrix. E.g.

    import numpy as np
    p = np.array([[1,2], [3,4]])
    g = np.array(range(20))
    g.shape = (4,5)
    g[0:2, 0:2] = p
    

    Here are the arrays:

    p

       array([[1, 2],
           [3, 4]])
    

    g:

    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19]])
    

    and the resulting g after assignment:

       array([[ 1,  2,  2,  3,  4],
           [ 3,  4,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19]])
    

提交回复
热议问题