Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python:: Adding array from each iteration to create new larger array

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]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading