Python List of np arrays to array

PythonArraysListNumpy

Python Problem Overview


I'm trying to turn a list of 2d numpy arrays into a 2d numpy array. For example,

dat_list = []
for i in range(10):
    dat_list.append(np.zeros([5, 10]))

What I would like to get out of this list is an array that is (50, 10). However, when I try the following, I get a (10,5,10) array.

output = np.array(dat_list)

Thoughts?

Python Solutions


Solution 1 - Python

you want to stack them:

np.vstack(dat_list)

Solution 2 - Python

Above accepted answer is correct for 2D arrays as you requested. For 3D input arrays though, vstack() will give you a surprising outcome. For those, use stack(, 0).

Solution 3 - Python

See https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html for details. You can use append, but will want to specify the axis on which to append.

dat_list.append(np.zeros([5, 10]),axis=0)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikeView Question on Stackoverflow
Solution 1 - PythonwimView Answer on Stackoverflow
Solution 2 - PythonAnandView Answer on Stackoverflow
Solution 3 - PythonMessypuddleView Answer on Stackoverflow