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

前端 未结 7 963
后悔当初
后悔当初 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:51

    Another elegant solution to the first question may be the insert command:

    p = np.array([[1,2],[3,4]])
    p = np.insert(p, 2, values=0, axis=1) # insert values before column 2
    

    Leads to:

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

    insert may be slower than append but allows you to fill the whole row/column with one value easily.

    As for the second question, delete has been suggested before:

    p = np.delete(p, 2, axis=1)
    

    Which restores the original array again:

    array([[1, 2],
           [3, 4]])
    
    0 讨论(0)
提交回复
热议问题