NumPy dstack()

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

import numpy as np

array1 = np.array([[0, 1], [2, 3]])
array2 = np.array([[4, 5], [6, 7]])

# stack the arrays stackedArray = np.dstack((array1, array2))
print(stackedArray) ''' Output [[[0 4] [1 5]] [[2 6] [3 7]]] '''

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

import numpy as np

# 3-D array with shape (2,2,2)
array1 = np.array([[[0, 1], [2,3]],
                   [[4, 5], [6, 7]]])
      
# 3-D array with shape (2,2,1)
array2 = np.array([[[4], [5]], 
                   [[6], [7]]])
      
# stack the arrays stackedArray = np.dstack((array1, array2))
print(stackedArray)

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

import numpy as np

array1 = np.array([[[0, 1], [2,3]],
                   [[4, 5], [6, 7]]])
      
array2 = np.array([[[4], [5], [6]], 
                   [[7], [8], [9]]])
      
# stack the arrays with invalid shapes stackedArray = np.dstack((array1, array2))
print(stackedArray)

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).