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?
vals.append(np.random.rand(2, 2))inside the loop, thenmat = np.vstack(vals)after the loop? In your example case, you could that even with a list comprehension.np.appendwill stack vertically - but you first have to take time to read its docs!np.appendis just a crudely written front end tonp.concatenate, making you think you are doing something like the list append method.vstackexample? If you look at the[source]for bothnp.appendandnp.vstackyou'll see that they have if-else` statements, prior to callingnp.concatenate. And what's wrong with areshapeafter?ifandreshapeare both cheap compared to the copying required by repeatedconcatenate.