What is the numpy.dstack() function in NumPy?

Overview

The dstack() function in NumPy is used to stack or arrange the given arrays in a sequence depth wise (that is, along the third axis), thereby creating an array of at least 3-D.

How the dstack() function works

Illustration of the "dstack()" function

Syntax

numpy.dstack(tup)
Syntax of the "dstack()" function in NumPy

Parameter value

The dstack() function takes the parameter value, tup, which represents a sequence of arrays having the same shape along all the axes except for the third axis.

Return value

The dstack() function returns an array of at least 3-D by stacking the input arrays.

Example

import numpy as np
# creating input arrays
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
# stacking the arrays sequential depth wise
stacked_array = np.dstack((a, b))
# printing the new array
print(stacked_array)

Explanation

  • Line 1: We import the numpy module.
  • Line 3-4: We create the input arrays a and b using the array() function.
  • Line 7: We vertically stack the arrays a and b using the dstack() function. Then, we assign the result to a variable called stacked_array.
  • Line 10: We print the newly stacked stacked_array array.

Free Resources