NumPy dstack()

The dstack() method stacks the sequence of input arrays depthwise.


dstack() Syntax

The syntax of dstack() is:

numpy.dstack(tup)

dstack() Argument

The dstack() method takes a single argument:

  • tup - a tuple of arrays to be stacked

Note: The shape of all arrays in a given tuple must be the same, except for the third dimension because we are stacking in axis 2 (depthwise).


dstack() Return Value

The dstack() method returns the depthwise stacked array.


Example 1: Stack Arrays of Different Shapes Depthwise

Output

[[[0 1 4]
  [2 3 5]]

 [[4 5 6]
  [6 7 7]]]

Here, we have stacked 2 arrays of different shapes.

The shape of array2 is (2, 2, 1), yet we could stack it with array1 of shape (2, 2, 2) because only the third dimension of array2 is different from array1.


Example 2: Stack Arrays Depthwise With Invalid Shapes

Output

ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 3

Here, the shape of array2 is (2, 3, 1), which conflicts while stacking with arrays of shape (2, 2, 2).