Advertisements
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 :
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)