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

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

    You can use:

    >>> np.concatenate([array1, array2, ...]) 
    

    e.g.

    >>> import numpy as np
    >>> a = [[1, 2, 3],[10, 20, 30]]
    >>> b = [[100,200,300]]
    >>> a = np.array(a) # not necessary, but numpy objects prefered to built-in
    >>> b = np.array(b) # "^
    >>> a
    array([[ 1,  2,  3],
           [10, 20, 30]])
    >>> b
    array([[100, 200, 300]])
    >>> c = np.concatenate([a,b])
    >>> c
    array([[  1,   2,   3],
           [ 10,  20,  30],
           [100, 200, 300]])
    >>> print c
    [[  1   2   3]
     [ 10  20  30]
     [100 200 300]]
    

    ~-+-~-+-~-+-~

    Sometimes, you will come across trouble if a numpy array object is initialized with incomplete values for its shape property. This problem is fixed by assigning to the shape property the tuple: (array_length, element_length).

    Note: Here, 'array_length' and 'element_length' are integer parameters, which you substitute values in for. A 'tuple' is just a pair of numbers in parentheses.

    e.g.

    >>> import numpy as np
    >>> a = np.array([[1,2,3],[10,20,30]])
    >>> b = np.array([100,200,300]) # initialize b with incorrect dimensions
    >>> a.shape
    (2, 3)
    >>> b.shape
    (3,)
    >>> c = np.concatenate([a,b])
    
    Traceback (most recent call last):
      File "", line 1, in 
        c = np.concatenate([a,b])
    ValueError: all the input arrays must have same number of dimensions
    >>> b.shape = (1,3)
    >>> c = np.concatenate([a,b])
    >>> c
    array([[  1,   2,   3],
           [ 10,  20,  30],
           [100, 200, 300]])
    

提交回复
热议问题