1

I want to create an array based on array generated from a for loop, however, I only get last array, how could I add arrays together

import numpy as np
x=np.array([1,1,3,3,5,5,5,5])
for xx in range(0,len(x),4):
       yy=x[xx:xx+4]
       zz=np.tile(yy,2)
print(zz) # EXPECTED z=[1 1 3 3 1 1 3 3 5 5 5 5 5 5 5 5]
1
  • The code inside the loop creates a new yy & zz every iteration, no aggregation, so why should anything else happen? Commented Dec 12, 2021 at 20:18

1 Answer 1

2

Every iteration in the loop you are overriding the zz you need to update it instead. this can be done by creating an empty list outside the loop and extending it each iteration.

Code:

import numpy as np

x=np.array([1,1,3,3,5,5,5,5])
zz = []

for xx in range(0,len(x),4):
       yy=x[xx:xx+4]
       zz.extend(np.tile(yy,2))
zz = np.array(zz)
print(np.array(zz))

Output:

[1 1 3 3 1 1 3 3 5 5 5 5 5 5 5 5]

Without Loop:

import numpy as np

x = np.array([1,1,3,3,5,5,5,5])
zz = np.concatenate(np.repeat(np.split(x, len(x)//4), 2, axis=0))
print(zz)
Sign up to request clarification or add additional context in comments.

2 Comments

It works perfectly now, THank you so much , I am gonna accept the answer, Also, may I ask you if you have any other ideas to do the same solution but without the need to for loop ?
@msci I added a solution without a loop :)

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.