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?

JavaScript

I can think of the following solution:

JavaScript

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:

JavaScript

Output:

JavaScript

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