What is NumPy Depth Stacking?

When NumPy arrays are stacked along the third axis(depth) then it is called depth stacking. In NumPy, you can achieve depth stacking using the numpy.dstack() function.

Syntax for Numpy dstack()

np.dstack(tuple)

You pass Numpy arrays in the form of list or tuple to the dstack() function.

Python program to depth stack 1-Dimensional Numpy Array

import numpy as np

x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
print('First array x:\n', x)
print('Second array y:\n', y)
print('Depth stacked array:\n', np.dstack((x,y)))

Output

First array x:
 [1 2 3 4]
Second array y:
 [5 6 7 8]
Depth stacked array:
 [[[1 5]
  [2 6]
  [3 7]
  [4 8]]]

Python program to depth stack 2-Dimensional Numpy Array

import numpy as np

x = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
y = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]])
print('First array x:\n', x)
print('Second array y:\n', y)
print('Depth stacked array:\n', np.dstack((x,y)))

Output

First array x:
 [[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
Second array y:
 [[11 12 13 14 15]
 [16 17 18 19 20]]
Depth stacked array:
 [[[ 1 11]
  [ 2 12]
  [ 3 13]
  [ 4 14]
  [ 5 15]]

 [[ 6 16]
  [ 7 17]
  [ 8 18]
  [ 9 19]
  [10 20]]]

Recommended Posts