Hello,
I am trying to generate an array out of the results of this iteration.
import numpy as np
num=3
for x in range(num+1):
a=np.array([2,x])
print(a)
Result:
[2 0] [2 1] [2 2] [2 3]
So, I would like to have an array
a = [2 0 2 1 2 2 2 3]
I have not figured out how to apply a np.concatenate as it does not allow me to assign a variable to each result.
Any ideas?
Thank you!
Solved! Go to Solution.
num=3
lst =[]
for x in range(num+1):
lst.append([2, x])
out = np.array(lst)
out
Out[4]:
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
out.ravel()
Out[5]: array([2, 0, 2, 1, 2, 2, 2, 3])
better
num=3
lst =[]
for x in range(num+1):
lst.extend([2, x])
out = np.array(lst)
out
Out[7]: array([2, 0, 2, 1, 2, 2, 2, 3])
better
skip iteration all together
num = 4
val = 2
a = np.empty(shape=(num, 2), dtype=np.int32)
a.fill(val)
a[:, 1] = np.arange(num)
a
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
a.ravel()
array([2, 0, 2, 1, 2, 2, 2, 3])
There are more efficient ways.
Also note, create the final array at the end
num=3
lst =[]
for x in range(num+1):
lst.append([2, x])
out = np.array(lst)
out
Out[4]:
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
out.ravel()
Out[5]: array([2, 0, 2, 1, 2, 2, 2, 3])
better
num=3
lst =[]
for x in range(num+1):
lst.extend([2, x])
out = np.array(lst)
out
Out[7]: array([2, 0, 2, 1, 2, 2, 2, 3])
better
skip iteration all together
num = 4
val = 2
a = np.empty(shape=(num, 2), dtype=np.int32)
a.fill(val)
a[:, 1] = np.arange(num)
a
array([[2, 0],
[2, 1],
[2, 2],
[2, 3]])
a.ravel()
array([2, 0, 2, 1, 2, 2, 2, 3])
There are more efficient ways.
Also note, create the final array at the end
Thank you Dan!