Array Concatenation and Stacking
What you'll learn: How to combine multiple NumPy arrays into single, larger arrays — essential for building training batches and merging datasets in ML workflows.
Why Combine Arrays?
In machine learning, you often need to merge separate data sources or combine individual samples into batches. Imagine you have three separate stacks of index cards (arrays), and you need to arrange them into one organized collection for training. NumPy provides several ways to do this efficiently.
The Core Functions
np.concatenate()
The most general function — joins arrays along an existing axis. You specify which dimension to join along.
import numpy as np
# Two batches of data (each has 3 samples, 2 features)
batch1 = np.array([[1, 2], [3, 4], [5, 6]])
batch2 = np.array([[7, 8], [9, 10]])
# Concatenate along axis 0 (stack rows)
combined = np.concatenate([batch1, batch2], axis=0)
# Result shape: (5, 2) - now 5 samples total
np.vstack() and np.hstack()
Convenient shortcuts: vstack stacks vertically (rows), hstack stacks horizontally (columns).
# Same as concatenate with axis=0
vertical = np.vstack([batch1, batch2])
# Add features horizontally
labels = np.array([[0], [1], [0]])
features_with_labels = np.hstack([batch1, labels])
# Shape: (3, 3)
np.stack()
Creates a new axis and stacks arrays along it — useful when combining samples into a batch dimension.
sample1 = np.array([1, 2, 3])
sample2 = np.array([4, 5, 6])
batch = np.stack([sample1, sample2], axis=0)
# Shape: (2, 3) - 2 samples of 3 features each
Key Takeaway: Use concatenate/vstack/hstack to merge along existing dimensions, and stack to create a new dimension — critical skills for assembling training data from multiple sources.