6

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

2 Answers 2

3

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.])
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.