Open In App

Numpy dstack() method-Python

Last Updated : 12 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.dstack() stacks arrays depth-wise along the third axis (axis=2). For 1D arrays, it promotes them to (1, N, 1) before stacking. For 2D arrays, it stacks them along axis=2 to form a 3D array.

Example:

Python
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

res = np.dstack((a, b))
print(res)

Output
[[[1 4]
  [2 5]
  [3 6]]]

Arrays a and b are stacked along the third axis, creating a 3D array with shape (1, 3, 2).

Syntax

numpy.dstack(tup)

Parameters:

  • tup (sequence of array_like): Arrays to be stacked depth-wise (axis=2); must have the same shape except along the third axis.

Returns: This method returns a stacked array with one more dimension (axis=2) than the input arrays.

Examples

Example 1: Depth-wise stacking of 2D arrays

Python
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

res = np.dstack((a, b))
print(res)

Output
[[[1 5]
  [2 6]]

 [[3 7]
  [4 8]]]

Each corresponding element from arrays a and b is stacked into a new depth layer.

Example 2: Stacking arrays of different shapes (raises an error)

Python
import numpy as np
a = np.array([[1, 2, 3]])
b = np.array([[4, 5]])

res = np.dstack((a, b))

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 3 and the array at index 1 has size 2...

Arrays must match in shape except along the stacking axis (axis=2).

Example 3: Depth-wise stacking with negative numbers

Python
import numpy as np
a = np.array([-1, -2, -3])
b = np.array([4, 5, 6])

res = np.dstack((a, b))
print(res)

Output
[[[-1  4]
  [-2  5]
  [-3  6]]]

Works with negative integers too. The resulting array stacks corresponding elements into a new depth dimension.


Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy