1. Home
  2. Docs
  3. numpy
  4. Stacking Arrays

Stacking Arrays

Stacking Arrays

Stacking involves joining a sequence of arrays along a new axis, either vertically (vstack) or horizontally (hstack).

Code Example:

import numpy as np

# Creating two 2D arrays
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

# Vertically stacking arrays a and b
vstacked = np.vstack((a, b))

# Horizontally stacking arrays a and b
hstacked = np.hstack((a, b))

print("Vertically Stacked:\n", vstacked)
print("\nHorizontally Stacked:\n", hstacked)
Python

Output

Vertically Stacked:
 [[1 2]
 [3 4]
 [5 6]
 [7 8]]

Horizontally Stacked:
 [[1 2 5 6]
 [3 4 7 8]]
Python

Explanation:

  • np.vstack((a, b)) stacks the arrays a and b vertically, adding b under a.
  • np.hstack((a, b)) stacks the arrays a and b horizontally, placing b to the right of a.

How can we help?