Convert a list of 2D numpy arrays to one 3D numpy array? Convert a list of 2D numpy arrays to one 3D numpy array? numpy numpy

Convert a list of 2D numpy arrays to one 3D numpy array?


newarray = np.dstack(mylist)

should work. For example:

import numpy as np# Here is a list of five 10x10 arrays:x = [np.random.random((10,10)) for _ in range(5)]y = np.dstack(x)print(y.shape)# (10, 10, 5)# To get the shape to be Nx10x10, you could  use rollaxis:y = np.rollaxis(y,-1)print(y.shape)# (5, 10, 10)

np.dstack returns a new array. Thus, using np.dstack requires as much additional memory as the input arrays. If you are tight on memory, an alternative to np.dstack which requires less memory is toallocate space for the final array first, and then pour the input arrays into it one at a time.For example, if you had 58 arrays of shape (159459, 2380), then you could use

y = np.empty((159459, 2380, 58))for i in range(58):    # instantiate the input arrays one at a time    x = np.random.random((159459, 2380))    # copy x into y    y[..., i] = x