How to insert zeros between elements in a numpy array?

Viewed 15455

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?

4 Answers

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)

You can simply do it with the insert function:

np.insert(x, [1,2,3], 0, axis=1)

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

Along the lines of your expand_dims, we can use stack:

In [742]: x=np.arange(1,7).reshape(2,-1)
In [743]: x
Out[743]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [744]: np.stack([x,x*0],axis=-1).reshape(2,-1)
Out[744]: 
array([[1, 0, 2, 0, 3, 0],
       [4, 0, 5, 0, 6, 0]])

stack uses expend_dims to add a dimension; it's like np.array but with more control over how the new axis is added. Thus it is a handy way of interspersing arrays.

The stack produces a (2,4,2) array which we reshape to (2,8).

x*0 could be replaced with np.zeros_like(x), or anything that creates the same size of zero array.

np.stack([x,x*0],axis=1).reshape(4,-1) to add 0 rows.

You needed to pad only one side of the new dimension:

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