![]() |
VOOZH | about |
The numpy.stack() function is used to join multiple arrays by creating a new axis in the output array. This means the resulting array always has one extra dimension compared to the input arrays. To stack arrays, they must have the same shape, and NumPy places them along the axis you specify.
Example: This example stacks two 1D arrays along a new axis to form a 2D array.
[[1 2 3] [4 5 6]]
Explanation: np.stack((a, b), axis=0) creates a new 0th axis and places arrays one below another.
numpy.stack(arrays, axis=0, out=None)
Parameters:
Example 1: This example shows how stacking the same 1D arrays along axis 0, 1, and -1 changes the output shape.
[[1 2 3] [4 5 6]] [[1 4] [2 5] [3 6]] [[1 4] [2 5] [3 6]]
Explanation:
Example 2: This example stacks two 2D arrays along axis 0, 1, and 2 to show how the new 3D structure changes.
[[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]] [[[ 1 2 3] [ 7 8 9]] [[ 4 5 6] [10 11 12]]] [[[ 1 7] [ 2 8] [ 3 9]] [[ 4 10] [ 5 11] [ 6 12]]]
Explanation:
Example 3: This example stacks two 3D arrays along axis 0, 1, 2, and 3 to demonstrate how stacking works with higher-dimension data.
Output
[[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]]
[[[10 20]
[30 40]]
[[50 60]
[70 80]]]]
[[[[ 1 2]
[ 3 4]]
[[10 20]
[30 40]]]
[[[ 5 6]
[ 7 8]]
[[50 60]
[70 80]]]]
[[[[ 1 2]
[10 20]]
[[ 3 4]
[30 40]]]
[[[ 5 6]
[50 60]]
[[ 7 8]
[70 80]]]]
[[[[ 1 10]
[ 2 20]]
[[ 3 30]
[ 4 40]]]
[[[ 5 50]
[ 6 60]]
[[ 7 70]
[ 8 80]]]]
Explanation: