Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Splitting Arrays in NumPy
Next article icon

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
importnumpyasnpa=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
importnumpyasnpa=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
importnumpyasnpa=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
importnumpyasnpa=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.


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp