NumPy np.stack()

We use the NumPy stack() function to join a sequence of arrays (same dimension) along a new axis.

NumPy Stack() Function Syntax

The stack() function provides a relatively simple syntax as reflected in the example below:

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

The function parameters are as follows:


  1. arrays – refers to the sequence of arrays to be concatenated. As mentioned, each array must be of the same shape.
  2. axis – specifies along which axis we connect the input arrays.
  3. out – specifies the destination path for the output array.

Return Value
The function returns a concatenated array with one more dimension than the input arrays.

Example 1

Consider the following example:

import numpy as np
arr_1 = np.array([[1,2,3],[4,5,6]])
arr_2 = np.array([[7,8,9],[10,11,12]])

concatenated =  np.stack((arr_1, arr_2), axis=0)
print(f"shape: {concatenated.shape}")

We use the stack() function to concatenate two arrays along axis zero in the previous code.

The resulting shape and array are as follows:

shape: (2, 2, 3)
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])

Example 2

We can also concatenate the two arrays along axis one as reflected in the following example:

arr_1 = np.array([[1,2,3],[4,5,6]])
arr_2 = np.array([[7,8,9],[10,11,12]])

concatenated =  np.stack((arr_1, arr_2), axis=1)
print(f"shape: {concatenated.shape}")

In this case, we specify the axis=1, which results in the following shape and array:

shape: (2, 2, 3)
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 4,  5,  6],
        [10, 11, 12]]])

NOTE: Although the shape of the array does not change, the order in which the elements are concatenated is altered.

Example 3

To stack the arrays along the last axis, we can specify the axis as a negative integer, as shown below:

concatenated =  np.stack((arr_1, arr_2), axis=-1)
print(f"shape: {concatenated.shape}")

The above snippet returns like the following example:

shape: (2, 3, 2)
array([[[ 1,  7],
        [ 2,  8],
        [ 3,  9]],

       [[ 4, 10],
        [ 5, 11],
        [ 6, 12]]])


This article explores the fundamentals and elements of the NumPy stack function. We also illustrate how to use the stack function in a set of scenarios.

Check out the Linux Hint website for more NumPy tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list