Home > Blockchain >  fill an array line by line in a loop
fill an array line by line in a loop

Time:10-01

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?

CodePudding user response:

Just wait to the end to convert the list of lists to a numpy array

a = []
for i in range(3):
    line = [i, i   1, i   2]
    a.append(line)
a = np.array(a)
print(a)

CodePudding user response:

Using numpy alone:

np.tile(np.arange(3), [3,1])   np.arange(3).reshape((3,1))

[[0 1 2]
 [1 2 3]
 [2 3 4]]

CodePudding user response:

This is a possible solution using numpy.vstack:

import numpy

rows = [numpy.array([i, i   1, i   2]) for i in range(3)]
matrix = numpy.vstack(rows)
print(matrix)

Output:

[[0 1 2]
 [1 2 3]
 [2 3 4]]

CodePudding user response:

I'm not sure if you want to be able to scale this. I would think that you can use .reshape() on the array. This also makes it scalable as it allows you to use -1 in one dimension, after which it will solve that dimension.

Additionally, I would just append to a and convert it to a numpy array afterwards. With that, your code becomes:

import numpy as np

a = []
nrows = 3  # change to increase number of rows
for i in range(nrows):
    a  = [i, i 1, i 2]
a = np.array(a).reshape(-1, 3)  # reshape to the format (x, 3)

  • Related