Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert zeros between elements in a numpy array?

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?

like image 633
Iter Ator Avatar asked Nov 05 '17 19:11

Iter Ator


People also ask

How do you add zeros to an array?

You can use numpy. pad , which pads default 0 to both ends of the array while in constant mode, specify the pad_width = (0, N) will pad N zeros to the right and nothing to the left: N = 4 np.

What is the use of zeros () function in NumPy?

The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy. int8.

How do you add a row of zeros to a NumPy Matrix?

Use the numpy. append() Function to Add a Row to a Matrix in NumPy. The append() function from the numpy module can add elements to the end of the array. By specifying the axis as 0, we can use this function to add rows to a matrix.


2 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)
like image 147
Divakar Avatar answered Sep 24 '22 11:09

Divakar


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]])
like image 38
Andreas K. Avatar answered Sep 21 '22 11:09

Andreas K.