Danjmp
Danjmp

Reputation: 63

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

Upvotes: 6

Views: 982

Answers (2)

jpp
jpp

Reputation: 164623

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.])

Upvotes: 3

xnx
xnx

Reputation: 25478

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.

Upvotes: 2

Related Questions