What is the numpy.stack() function in Python?

Overview

In Python, we use the stack() function to join or concatenate a sequence of input arrays along a new axis.

Syntax

numpy.stack(arrays, axis=0, out=None)
Syntax for the stack() function

Parameters

The stack() function takes the following parameter values:

  • arrays (required): These are the input arrays to be concatenated.
  • axis (optional): This is the given axis along which we append the input arrays.
  • out (optional): This is the destination path for the result.

Return value

The stack() function returns the concatenated array.

Example 1

import numpy as np
# creating input arrays
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])
# concatenating the arrays
myarray = np.stack((a, b), axis = 0)
# printing the concatenated array
print(myarray)

Explanation

  • Line 1: We import the NumPy module.
  • Line 4–5: We create input arrays, a and b, using the array() function.
  • Line 8: We concatenate the input arrays using the stack() function. The result is assigned to a variable, myArray.
  • Line 11: We print the concatenated array, myArray.

Example 2

import numpy as np
# creating input arrays
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8, 9], [10, 11, 12]])
# concatenating the arrays
myarray = np.stack((a, b), axis = -1)
# printing the concatenated array
print(myarray)

Explanation

The code above is similar to Example 1 except that the arrays are concatenated along the last axis, i.e axis = -1.

Free Resources