python - increase array size and initialize new elements to zero -


i have array of size 2 x 2 , want change size 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 shape didn't , append can append row, not column. don't want iterate through each row add column.

is there vectorized way of in matlab: a(:,3:4) = 0; , a(3,:) = 0; converted a 2 x 2 3 x 4. thinking is there similar way in python?

in python, if input numpy array, can use np.lib.pad pad zeros around -

import numpy np  = 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]:  # input: 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]])  # 0 padded numpy array 

if don't want math of how many zeros pad, can let code given output array size -

in [29]: 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, can start off 0 initialized output array , put input elements a -

in [38]: 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]] =  in [41]: a_new out[41]:  array([[1, 2, 0, 0],        [2, 3, 0, 0],        [0, 0, 0, 0]]) 

in matlab, can use padarray -

a_new  = padarray(a,[1 2],'post') 

sample run -

>> 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 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -