NumPy - stack() function

The NumPy stack() function joins a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.

Syntax

numpy.stack(arrays, axis=0, out=None)

Parameters

 arrays Required. Specify arrays (array_like) to be stacked. Each array must have the same shape. axis Optional. Specify axis in the result array along which the input arrays are stacked. out Optional. Specify output array for the result. The default is None. If provided, it must have the same shape as output.

Return Value

Returns the stacked array. It has one more dimension than the input arrays.

Example:

In the example below, stack() function is used to stack two given arrays.

import numpy as np

Arr1 = np.array([[10,20],[30, 40]])
Arr2 = np.array([[50,60],[70, 80]])

#stacking arrays along axis=0
Arr3 = np.stack((Arr1, Arr2), axis=0)
#stacking arrays along axis=1
Arr4 = np.stack((Arr1, Arr2), axis=1)

#displaying results
print("Arr1 is:")
print(Arr1)
print("\nArr2 is:")
print(Arr2)
print("\nArr3 is:")
print(Arr3)
print("\nArr4 is:")
print(Arr4)

The output of the above code will be:

Arr1 is:
[[10 20]
[30 40]]

Arr2 is:
[[50 60]
[70 80]]

Arr3 is:
[[[10 20]
[30 40]]

[[50 60]
[70 80]]]

Arr4 is:
[[[10 20]
[50 60]]

[[30 40]
[70 80]]]

Example:

Consider one more example.

import numpy as np

Arr1 = np.array([10, 20, 30])
Arr2 = np.array([40, 50, 60])

#stacking arrays along axis=0
Arr3 = np.stack((Arr1, Arr2), axis=0)
#stacking arrays along axis=1
Arr4 = np.stack((Arr1, Arr2), axis=1)

#displaying results
print("Arr1 is:")
print(Arr1)
print("\nArr2 is:")
print(Arr2)
print("\nArr3 is:")
print(Arr3)
print("\nArr4 is:")
print(Arr4)

The output of the above code will be:

Arr1 is:
[10 20 30]

Arr2 is:
[40 50 60]

Arr3 is:
[[10 20 30]
[40 50 60]]

Arr4 is:
[[10 40]
[20 50]
[30 60]]

❮ NumPy - Functions

5