DSLBG13
DSLBG13

Reputation: 23

Add element after each element in numpy array python

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!

Upvotes: 1

Views: 1838

Answers (2)

rambi
rambi

Reputation: 1259

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

Upvotes: 3

Aayman Khalid
Aayman Khalid

Reputation: 468

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!

Upvotes: 3

Related Questions