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

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

    The shortest in terms of lines of code i can think of is for the first question.

    >>> import numpy as np
    >>> p = np.array([[1,2],[3,4]])
    
    >>> p = np.append(p, [[5,6]], 0)
    >>> p = np.append(p, [[7],[8],[9]],1)
    
    >>> p
    array([[1, 2, 7],
       [3, 4, 8],
       [5, 6, 9]])
    

    And the for the second question

        p = np.array(range(20))
    >>> p.shape = (4,5)
    >>> p
    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19]])
    >>> n = 2
    >>> p = np.append(p[:n],p[n+1:],0)
    >>> p = np.append(p[...,:n],p[...,n+1:],1)
    >>> p
    array([[ 0,  1,  3,  4],
           [ 5,  6,  8,  9],
           [15, 16, 18, 19]])
    

提交回复
热议问题