Stacking Arrays in NumPy
In real-world data processing, information often comes from multiple sources. NumPy allows you to combine arrays efficiently using stacking operations.
In this lesson, you will learn how to stack arrays vertically, horizontally, and along custom axes.
Understanding Array Stacking
Stacking means combining multiple arrays into a single array. The most commonly used stacking functions are:
np.concatenate()np.vstack()np.hstack()np.stack()
Sample Arrays
We will use the following arrays throughout this lesson.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([40, 50, 60])
print(a)
print(b)
These arrays represent numeric data collected from two different sources.
Horizontal Stacking
Horizontal stacking joins arrays side by side.
horizontal = np.hstack((a, b))
print(horizontal)
Output:
[10 20 30 40 50 60]
This creates a single array by appending elements from left to right.
Vertical Stacking
Vertical stacking combines arrays row-wise.
vertical = np.vstack((a, b))
print(vertical)
Output:
[[10 20 30]
[40 50 60]]
Each original array becomes a separate row.
Using np.concatenate()
The np.concatenate() function gives more control over how arrays are joined.
combined = np.concatenate((a, b))
print(combined)
Output:
[10 20 30 40 50 60]
By default, concatenation happens along the first axis.
Stacking Along a New Axis
The np.stack() function adds a new dimension while stacking.
stacked = np.stack((a, b))
print(stacked)
Output:
[[10 20 30]
[40 50 60]]
This results in a two-dimensional array.
Stacking with Axis Control
You can control how stacking happens using the axis parameter.
stacked_axis1 = np.stack((a, b), axis=1)
print(stacked_axis1)
Output:
[[10 40]
[20 50]
[30 60]]
Each element from both arrays is paired row-wise.
Real-World Example
Consider monthly sales data collected from two regions:
- Horizontal stacking → combine all sales values
- Vertical stacking → compare regions side by side
- Stack with axis → align related data points
Stacking helps structure data for analysis and visualization.
Practice Exercise
Task
- Create two arrays with 5 numeric values each
- Stack them horizontally and vertically
- Use
np.stack()with different axis values
What’s Next?
In the next lesson, you will learn about Matrix Operations in NumPy, which are essential for scientific computing and machine learning.