python - increase array size and initialize new elements to zero

后端 未结 3 417
小蘑菇
小蘑菇 2021-01-03 06:52

I have an array of a size 2 x 2 and I want to change the size to 3 x 4.

A = [[1 2 ],[2 3]]
A_new = [[1 2 0 0],[2 3 0 0],[0 0 0 0]]

I tried

3条回答
  •  执笔经年
    2021-01-03 06:59

    In Python, if the input is a numpy array, you can use np.lib.pad to pad zeros around it -

    import numpy as np
    
    A = np.array([[1, 2 ],[2, 3]])   # Input
    A_new = np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0)) # Output
    

    Sample run -

    In [7]: A  # Input: A numpy array
    Out[7]: 
    array([[1, 2],
           [2, 3]])
    
    In [8]: np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0))
    Out[8]: 
    array([[1, 2, 0, 0],
           [2, 3, 0, 0],
           [0, 0, 0, 0]])  # Zero padded numpy array
    

    If you don't want to do the math of how many zeros to pad, you can let the code do it for you given the output array size -

    In [29]: A
    Out[29]: 
    array([[1, 2],
           [2, 3]])
    
    In [30]: new_shape = (3,4)
    
    In [31]: shape_diff = np.array(new_shape) - np.array(A.shape)
    
    In [32]: np.lib.pad(A, ((0,shape_diff[0]),(0,shape_diff[1])), 
                                  'constant', constant_values=(0))
    Out[32]: 
    array([[1, 2, 0, 0],
           [2, 3, 0, 0],
           [0, 0, 0, 0]])
    

    Or, you can start off with a zero initialized output array and then put back those input elements from A -

    In [38]: A
    Out[38]: 
    array([[1, 2],
           [2, 3]])
    
    In [39]: A_new = np.zeros(new_shape,dtype = A.dtype)
    
    In [40]: A_new[0:A.shape[0],0:A.shape[1]] = A
    
    In [41]: A_new
    Out[41]: 
    array([[1, 2, 0, 0],
           [2, 3, 0, 0],
           [0, 0, 0, 0]])
    

    In MATLAB, you can use padarray -

    A_new  = padarray(A,[1 2],'post')
    

    Sample run -

    >> A
    A =
         1     2
         2     3
    >> A_new = padarray(A,[1 2],'post')
    A_new =
         1     2     0     0
         2     3     0     0
         0     0     0     0
    

提交回复
热议问题