• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:17 mins read
You are currently viewing How to Use NumPy stack() in Python

NumPy stack() function is used to stack or join the sequence of given arrays along a new axis. It generates a single array by taking elements from the sequence of arrays having the same shape. The returned array has 1 more dimension than the input arrays for example you are stacked two 1-D arrays using this function it will return the 2-D NumPy array.

In this article, I will explain NumPy stack() function syntax and using its parameters how you can stack the sequence of arrays along the new axis with examples.

1. Quick Examples of NumPy stack()

If you are in a hurry, below are some quick examples of how to use Python NumPy stack() function.


# Quick examples of numpy stack()

# Example 1 : Use stack() function 
#  Get the 2-d array
arr = np.array([1, 2, 3])
arr1 = np.array([4, 5, 6])
arr2 = np.stack((arr, arr1), axis = 0)

# Example 2 : Get the 2-D stacked array
arr2 = np.stack((arr, arr1), axis = 1)

# Example 3 : Get the stacked array along = -1
arr2 = np.stack((arr, arr1), axis = -1)

# Example 4 : Get the stacked array of 3-D 
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr1 = np.array([[2, 4, 6],[5, 3, 1]])
arr2 = np.stack((arr, arr1), axis = 0)

# Example 5 : Stack the arrays along axis = 1
arr2 = np.stack((arr, arr1), axis = 1)

# Example 6 : Stack the arrays along axis = -1
arr2 = np.stack((arr, arr1), axis = -1)

2. Syntax of NumPy stack()

Following is the syntax of the stack() function.


# Syntax of Use stack() 
numpy.stack(arrays, axis=0, out=None)

2.1 Parameters of the stack()

Following is the parameter of the stack().

  • arr –  It contains a sequence of arrays of the same shape. these arrays are to be stacked as a parameter and return a single NumPy array.
  • axis – This parameter specifies the axis along which the arrays will be stacked. The default value is 0, meaning the arrays will be stacked along a new axis at the beginning. If you specify a different axis, the arrays will be stacked along that axis. If you set axis to -1, it means the arrays will be stacked along the last axis.
  • out – This parameter is optional and represents the array into which the output is placed. If not specified, a new array is created.

2.2 Return Value of the stack()

It returns the stacked array, where the dimensions are 1 more than the input arrays. of the given arrays.

3. Usage of the NumPy stack()

NumPy stack() function is used to stack the sequence of arrays along a new axis. In order to join two arrays, the Python NumPy module provides different types of functions which are concatenate(), stack(), vstack(), and hstack().

Below I have provided an image that explains how stack() function works, I hope it will give you a better understanding.

NumPy stack
numpy.stack(x, y)

Create two 1-D NumPy arrays using numpy.array() function and pass them into this function along axis=0, it will return the stacked array of the 2-D array.

Here, the np.stack() function is used to stack the two 1-dimensional arrays along a new axis (axis=0). The result is stored in the variable arr2. The stack() function is used here to combine the two 1-dimensional arrays into a 2-dimensional array along the specified axis (axis=0 in this case).


# Import numpy module
import numpy as np

# Create input array 
arr = np.array([1, 2, 3])
print("First array:\n",arr)
arr1 = np.array([4, 5, 6])
print("Second array:\n",arr1)

# Use stack() function 
# Get the 2-D array
arr2 = np.stack((arr, arr1), axis = 0)
print("Stacked array:\n",arr2) 

Yields below output.

NumPy stack

This time you pass the arrays along with axis=1 into this function, it will return the stacked array of 2-D NumPy array.

If you pass axis=1 to the np.stack() function, it will stack the arrays along the second axis. Now, the arrays are stacked along the second axis, resulting in a 2-dimensional array where each original array forms a column.


# Use stack() function 
# Get the 2-D array along the second axis
arr2 = np.stack((arr, arr1), axis = 1)
print("Stacked array along axis 1:\n", arr2)

# Output:
# Stacked array along axis 1:
#  [[1 4]
#  [2 5]
#  [3 6]]
NumPy stack
numpy.stack(x, y)

When you pass axis=-1 to the np.stack() function, it will stack the arrays along the last axis, and for 1-D arrays, the last axis is 1. In this case, since the arrays are 1-dimensional, specifying axis=-1 or axis=1 results in the same stacking behavior.


# Get the stacked array along axis = -1
arr2 = np.stack((arr, arr1), axis = -1)
print("Stacked array along last axis:\n", arr2)

# Output:
# Stacked array along last axis:
#  [[1 4]
#  [2 5]
#  [3 6]]

4. Stack the 2-D NumPy Arrays

If you want to stack two 2-dimensional NumPy arrays, you can use the np.stack() function as well. For instance, arr1 and arr2 are both 2-dimensional arrays, and they are stacked along a new axis (axis=0). The result is a 3-dimensional array.


# Create 2-D array 
arr = np.array([[1, 2, 3], [4, 5, 6]])
arr1 = np.array([[2, 4, 6],[5, 3, 1]])

# Get the stacked array of 3-D 
arr2 = np.stack((arr, arr1), axis = 0)
print("Stacked 3-D array:\n", arr2)

# Output:
# Stacked 3-D array:
#  [[[1 2 3]
#   [4 5 6]]

#  [[2 4 6]
#   [5 3 1]]]

4.1 Stack the Arrays along axis = 1

Stack the 2-D arrays along the axis=1, it will return the stacked array of 3-D array. in which 1st dimension has 1st-row elements and the second dimension has 2nd-row elements.


# Stack the arrays along axis = 1
arr2 = np.stack((arr, arr1), axis = 1)
print("Stacked 2-D array along axis 1:\n", arr2)

# Output:
# Stacked 2-D array along axis 1:
#  [[[1 2 3]
#  [2 4 6]]

#  [[4 5 6]
#  [5 3 1]]]

4.2 Stack the Arrays along axis = -1

Stack the 2-D arrays along the last axis(-1), it will return the stacked array of 3-D array, in which the 1st dimension has 1st column elements and the second dimension has 2nd column elements.


# Stack the arrays along axis = -1
arr2 = np.stack((arr, arr1), axis = -1)
print("Stacked array along last axis:\n", arr2)

# Output:
# Stacked array along last axis:
# [[[1 2]
#  [2 4]
# [3 6]]

# [[4 5]
#  [5 3]
#  [6 1]]]

Frequently Asked Questions

What does the stack() function in NumPy do?

The np.stack() function in NumPy is used to join a sequence of arrays along a new axis. It takes a sequence of arrays as input and returns a new array formed by stacking the input arrays along a specified axis.

Can I stack arrays of different shapes using np.stack()?

When using np.stack(), the arrays being stacked must have the same shape along the specified axis. If the arrays have different shapes, you will encounter a ValueError. The reason is that np.stack() expects the input arrays to have consistent shapes so that they can be stacked along the specified axis.

How does np.stack() differ from np.concatenate()?

While both functions can be used to combine arrays, np.stack() is specifically designed to introduce a new axis for stacking, creating a higher-dimensional array. np.concatenate(), on the other hand, concatenates arrays along an existing axis.

How can I stack 2D arrays along the columns using np.stack()?

To stack 2D arrays along the columns using np.stack(), you need to set the axis parameter to 1. For example, arr1 and arr2 are 2D arrays, and np.stack() is used to stack them along axis 1. The output will be a 3D array where each original array forms a column in the new array.

What happens if I don’t specify the axis parameter in np.stack()?

If the axis parameter is not specified, the default value is 0. This means the arrays will be stacked along a new axis at the beginning, creating a higher-dimensional array.

In what scenarios is np.stack() particularly useful?

np.stack() is useful when you want to explicitly introduce a new axis and stack arrays along that axis, especially when dealing with arrays of different dimensions. It is commonly used to create higher-dimensional arrays from a sequence of arrays.

Conclusion

In this article, I have explained numpy.stack() and using this how you can stack the sequence of given arrays into a single array along a new axis with examples.

Malli

Malli is an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly articles. Over the years, he has written hundreds of articles in Pandas, NumPy, Python, and takes pride in ability to bridge the gap between technical experts and end-users.