Suppose I have a loop that creates an array, line by line, starting from an empty array. Example:
import numpy
a = []
for i in range(3):
line = numpy.array([i, i + 1, i + 2])
a = numpy.append(a, line)
print(a)
This creates an array a = [0. 1. 2. 1. 2. 3. 2. 3. 4.], but I rather want a 3x3 array as:
[[0. 1. 2.]
[1. 2. 3.]
[2. 3. 4.]]
If I use numpy.vstack the code does not work when a=[]
import numpy
a = []
for i in range(3):
line = numpy.array([i, i + 1, i + 2])
a = numpy.vstack([a, line]) # Error here
print(a)
As a solution I could insert an if:
import numpy
a = []
for i in range(3):
line = numpy.array([i, i + 1, i + 2])
if (len(a) == 0):
a = numpy.append(a, line)
else:
a = numpy.vstack([a, line])
print(a)
This seems however rather cumbersome.
Is there a better way to just "add a line to the array a" with a single line that works in all cases?