Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy - Insert an array of zeros after specified indices

My code is:

x=np.linspace(1,5,5)

a=np.insert(x,np.arange(1,5,1),np.zeros(3))

The output I want is:

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

The error I get is:

ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing result of shape (4,)

When I do:

x=np.linspace(1,5,5)

a=np.insert(x,np.arange(1,5,1),0)

The out is:

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

Why it doesn't work when I try to insert an array?

P.S. I I cannot use loops

like image 476
Danjmp Avatar asked Nov 08 '18 13:11

Danjmp


People also ask

How do you make a NumPy array of all zeros?

zeros() function is one of the most significant functions which is used in machine learning programs widely. This function is used to generate an array containing zeros. The numpy. zeros() function provide a new array of given shape and type, which is filled with zeros.

How do you add a column of zeros to a NumPy array?

In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.

How do you fill an array with zeros in Python?

zeros() function is used which returns a new array of given shape and type, with zeros.

Are NumPy arrays zero indexed?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.


2 Answers

You can use np.repeat to feed repeated indices. For a 1d array, thhe obj argument for np.insert reference individual indices.

x = np.linspace(1, 5, 5)

a = np.insert(x, np.repeat(np.arange(1, 5, 1), 3), 0)

array([ 1.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  3.,  0.,  0.,  0.,  4.,
        0.,  0.,  0.,  5.])
like image 197
jpp Avatar answered Oct 17 '22 12:10

jpp


Another option:

np.hstack((x[:,None], np.zeros((5,3)))).flatten()[:-3]

gives:

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

That is, pretend x is a column vector and stack a 5x3 block of zeros to the right of it and then flatten.

like image 2
xnx Avatar answered Oct 17 '22 13:10

xnx