Skip to content
Advertisement

Numpy append 2D array in for loop over rows

I want to append a 2D array created within a for-loop vertically.
I tried append method, but this won’t stack vertically (I wan’t to avoid reshaping the result later), and I tried the vstack() function, but this won’t work on an empty array. Does anyone know how to solve this?

import numpy as np
mat = np.array([])
for i in np.arange(3):
    val = np.random.rand(2, 2)
    mat = np.append(mat,val)

I can think of the following solution:

for i in np.arange(3):
    val = np.random.rand(2, 2)
    if i==0:
        mat = val
    else:
        mat = np.vstack((mat,val))

Is there a solution where I just append the values ‘val’ without specifying an extra if-else statement?

Advertisement

Answer

Use np.empty to initialize an empty array and define the axis you want to append across:

import numpy as np
mat = np.empty((0,2))
for i in np.arange(3):
    val = np.random.rand(2, 2)
    mat = np.append(mat,val, axis=0)
print(mat)

Output:

[[0.08527627 0.40567273]
 [0.39701354 0.72642426]
 [0.17540761 0.02579183]
 [0.76271521 0.83032347]
 [0.08105248 0.67986726]
 [0.48079453 0.37454798]]

However, as stated in my comment, if you need to append a lot of times you should look into initializing an array of the correct size then assigning values over using np.append() or appending to a list instead (if you do not know the size of the array) and then creating a numpy array after

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement