numpy.dstack() – The NumPy dstack Python Function

Introduction to NumPy dstack

Using the numpy.dstack() function, we can obtain the combined array index by index and save it as a stack.

Stack arrays in order of depth (along the third axis). After reshaping 2-D arrays of shape (M, N) to (M, N,1) and 1-D arrays of shape (N,) to (N, N,1). This is identical to concatenation along the third axis (1, N,1). Rebuilds arrays that have been split by the split.

This function works well with arrays of up to three dimensions. For pixel data having a height (first axis), width (second axis), and r/g/b channels, for example (third axis). More broad stacking and concatenation operations are provided by the functions concatenate, stack, and block.

Syntax:

numpy.dstack(tup)

Parameters:

  • tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.

Return: Return combined array index by index.

Code Examples of NumPy dstack

Example 01:

# welcome to softhunt.net
# import numpy
import numpy as np

arr1 = np.array([0, 1, 3])
arr2 = np.array([5, 7, 9])

# using numpy.dstack() method
print(np.dstack((arr1, arr2)))

Output:

[[[0 5]
  [1 7]
  [3 9]]]

Example 02:

# welcome to softhunt.net
# import numpy
import numpy as np

arr1 = np.array([10, 20, 30])
arr2 = np.array([40, 50, 60])

# using numpy.dstack() method
print(np.dstack((arr1, arr2)))

Output:

[[[10 40]
  [20 50]
  [30 60]]]

FAQs

The NumPy Stack Python Function

To join a sequence of same-dimension arrays along a new axis, use the numpy.stack() function. The axis parameter defines the new axis index in the result’s dimensions. For example, if axis=0, the first dimension will be 0, and if axis=-1, the last dimension would be 1.

What is NumPy best for?

NumPy (Numerical Python) is a Python library for linear algebra. It is a critical library that practically all data science and machine learning Python packages, such as SciPy (Scientific Python), Matplotlib (plotting library), Scikit-learn, and others, depend on to some level.

NumPy is a Python package. That allows you to perform mathematical and logical operations on Arrays. Python has a lot of handy capabilities for working with n-arrays and matrices.

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. numpy.stack()
  2. numpy.vstack()
  3. numpy.hstack()

Leave a Comment