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
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 arraysa = np.array([1, 2, 3, 4, 5])b = np.array([6, 7, 8, 9, 10])# stacking the arrays sequential depth wisestacked_array = np.dstack((a, b))# printing the new arrayprint(stacked_array)
Explanation
- Line 1: We import the
numpymodule. - Line 3-4: We create the input arrays
aandbusing thearray()function. - Line 7: We vertically stack the arrays
aandbusing thedstack()function. Then, we assign the result to a variable calledstacked_array. - Line 10: We print the newly stacked
stacked_arrayarray.