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:
Pythonimportnumpyasnpa=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
Pythonimportnumpyasnpa=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)
Pythonimportnumpyasnpa=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
Pythonimportnumpyasnpa=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.