ICoder
ICoder

Reputation: 199

Padding 1D NumPy array with zeros to form 2D array

I have a numpy array:

arr=np.array([0,1,0,0.5])

I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. In short, every element is repeated thrice, zero as it is and non-zero has 2 preceding 0 and then the number itself. It is as follows:

([0,1,0,0.5])=0,0,0, [for index 0]
              0,0,1 [for index 1]
              0,0,0 [for index 2, which again has a zero] and
              0,0,0.5

final output should be:

new_arr=[0,0,0,0,0,1,0,0,0,0,0,0.5]

np.repeat() repeats all the array elements n number of times, but i dont want that exactly. How should this be done? Thanks for the help.

Upvotes: 1

Views: 1328

Answers (2)

hpaulj
hpaulj

Reputation: 231655

A variant on the pad idea is to concatenate a 2d array of zeros

In [477]: arr=np.array([0,1,0,0.5])
In [478]: np.column_stack([np.zeros((len(arr),2)),arr])
Out[478]: 
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  1. ],
       [ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0.5]])
In [479]: _.ravel()
Out[479]: 
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0.5])

or padding in the other direction:

In [481]: np.vstack([np.zeros((2,len(arr))),arr])
Out[481]: 
array([[ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  1. ,  0. ,  0.5]])
In [482]: _.T.ravel()
Out[482]: 
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0.5])

Upvotes: 0

cs95
cs95

Reputation: 403020

A quick reshape followed by a call to np.pad will do it:

np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant')

Output:

array([[ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  1. ],
       [ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0.5]])

You'll want to flatten it back again. That's simply done by calling .reshape(-1, ).

>>> np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant').reshape(-1, )
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
    0.5])

Upvotes: 3

Related Questions