The NumPy stack() method joins a sequence of arrays along a new axis.
Here, the stack() method combines two 2-D arrays along a new axis, resulting in a 3D array.
stack() Syntax
The syntax of stack() is:
numpy.stack((array1, array2, …), axis = 0, out)
stack() Arguments
The stack() method takes the following arguments:
(array1, array2, …)- the sequence of arrays to be joinedaxis(optional) - defines the dimension in which the arrays are joinedout(optional) - destination to store the result.dtype(optional) - datatype of the resultant array
Notes:
- Only one of
outanddtypearguments can be passed. - The shape of all arrays in the input tuple should be the same.
stack() Return Value
The stack() method returns the joined array.
Example 1: Stack Three Arrays
Output
[[[ 1 2] [ 3 4]] [[ 5 6] [ 7 8]] [[ 9 10] [11 12]]]
Here, the stack() method joined three 2-D arrays and returned a 3-D array.
Notice we haven't passed the axis argument. So the axis is 0 by default and the arrays are stacked row-wise (vertically).
Note:
stack(): Adds a new dimension and combines arrays into a higher-dimensional array.concatenate(): Joins arrays along an existing axis without introducing a new dimension
Example 2: Stack Two Arrays in Different Dimensions
Output
Joining the array when axis = 0 [[0 1] [2 3]] Joining the array when axis = 1 [[0 2] [1 3]]
Here, when the axis is 0, the arrays are stacked row-wise, and when axis is 1, the arrays are stacked column-wise.
Example 3: Return an Existing Array as Stacked Array
In our previous examples, the stack() function generated a new array as output.
However, we can use an existing array to store the output using the out argument.
Output
[[[ 0. 1.] [ 2. 3.]] [[10. 11.] [12. 13.]]]
Note: The shape of the output array must match the shape of the stacked array, otherwise we will get an error.
Example 4: Specify the Datatype of a Stacked Array
We can change the data type of the stacked array by passing the dtype argument.
Output
[[['0' '1'] ['2' '3']] [['10' '11'] ['12' '13']]]