user32145 - 4 months ago 23

Python Question

Is there a way to create a 3d numpy array by appending 2d numpy arrays? What I currently do is append my 2d numpy array into an initialized list of pre determined 2d numpy array, i.e., List=[np.zeros((600,600))]. After appending all my 2d numpy arrays I use numpy.dstack to create 3d numpy array. I think this is not a very efficient method. Any suggestions.

Answer

The most efficient way is to initialize the 3d array first and then sequentially write your data into it. Efficiency here is increased by avoiding unnecessary copies. The gains are however minimal - as long as you are not working with very large arrays (in either of the 3 dimensions).

```
import numpy as np
arr = np.empty(shape=(2, 100, 100))
arr[0,:,:] = array_2d_1
arr[1,:,:] = array_2d_2
```

Source (Stackoverflow)

Comments