How to insert zeros between elements in a numpy array?

0

Issue

I have an nd array, for example this:

x = np.array([[1,2,3],[4,5,6]])

I would like to double the size of the last dimension, and insert zeroes between the elements to fill the space. The result should look like this:

[[1,0,2,0,3,0],[4,0,5,0,6,0]]

I tried to solve it using expand_dims and pad. But the pad function inserts zeroes not just after each value in the last dimension. The shape of it’s result is (3, 4, 2), but it should be (2,3,2)

y = np.expand_dims(x,-1)
z = np.pad(y, (0,1), 'constant', constant_values=0)
res = np.reshape(z,[-1,2*3]

Result of my code:

array([[1, 0, 2, 0, 3, 0],
       [0, 0, 4, 0, 5, 0],
       [6, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

How is it possible with pad to insert zeroes in the last dimension after each element? Or is there any better way to solve the problem?

Solution

Simply initialize output array and assign with slicing

m,n = x.shape
out = np.zeros((m,2*n),dtype=x.dtype)
out[:,::2] = x

Alternatively with stacking –

np.dstack((x,np.zeros_like(x))).reshape(x.shape[0],-1)

Answered By – Divakar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More