Contruct 3d array in numpy from existing 2d array

Viewed 33811

During preparing data for NumPy calculate. I am curious about way to construct:

myarray.shape => (2,18,18)

from:

d1.shape => (18,18)
d2.shape => (18,18)

I try to use NumPy command:

hstack([[d1],[d2]])

but it looks not work!

4 Answers
arr3=np.dstack([arr1, arr2])

arr1, arr2 are 2d array shape (256,256), arr3: shape(256,256,2)

A lot of versatility is provided by the np.stack() function. You can say:

>>> d3 = np.stack([d1, d2])
>>> d3.shape
(2, 18, 18)

However you can also specify the axis, along which the arrays get joined. So if you wanted to join channels of a RGB image, you say:

>>> d3 = np.stack([d1, d2], axis=-1)
>>> d3.shape
(18, 18, 2)
Related