1

I am just starting off with numpy and am trying to create a function that takes in an array (x), converts this into a np.array, and returns a numpy array with 0,0,0,0 added after each element.

It should look like so:

input array: [4,5,6]

output: [4,0,0,0,0,5,0,0,0,0,6,0,0,0,0]

I have tried the following:

   import numpy as np
   x = np.asarray([4,5,6])
   y = np.array([])
   for index, value in enumerate(x):
        y = np.insert(x, index+1, [0,0,0,0])
        print(y)

which returns:

[4 0 0 0 0 5 6]
[4 5 0 0 0 0 6]
[4 5 6 0 0 0 0]

So basically I need to combine the output into one single numpy array rather than three lists.

Would anybody know how to solve this?

Many thanks!

2 Answers 2

3

Use the numpy .zeros function !

import numpy as np

inputArray = [4,5,6]

newArray = np.zeros(5*len(inputArray),dtype=int)
newArray[::5] = inputArray

In fact, you 'force' all the values with indexes 0,5 and 10 to become 4,5 and 6.

so _____[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

becomes [4 0 0 0 0 5 0 0 0 0 6 0 0 0 0]

>>> newArray
array([4, 0, 0, 0, 0, 5, 0, 0, 0, 0, 6, 0, 0, 0 ,0])
Sign up to request clarification or add additional context in comments.

1 Comment

So just to make sure I understood the code correctly:So just to make sure I understood the code correctly: numberOfZeros = 4 inputArray = [4,5,6] newArray = np.zeros((numberOfZeros+1)*len(inputArray),dtype=int) ##creates newArray with space for the inputArray + zeroes newArray[::(numberOfZeros+1)] = inputArray ## plugs in the input values, but could you explain this to me? Thanks!
3

I haven't used numpy to solve this problem,but this code seems to return your required output:

a = [4,5,6]
b = [0,0,0,0]
c = []
for x in a:
   c = c + [x] + b
print(c)

I hope this helps!

1 Comment

That seems so simple now! Thank you!

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.