Stacking and Splitting
Python · NumPy Library
Theory
Stacking joins arrays into one. np.concatenate([a, b], axis=0) joins along an existing axis; axis=0 adds rows and axis=1 adds columns. np.vstack puts arrays on top of each other (more rows) and np.hstack places them side by side (more columns). np.column_stack turns several 1-D arrays into the columns of a table, which is a quick way to build a feature matrix.
The sizes must agree on every axis except the one you join along: to vstack, both arrays need the same number of columns. Splitting is the reverse: np.split(arr, 3) cuts into 3 equal pieces and fails if the size does not divide evenly, while np.array_split allows unequal pieces. np.split(arr, [2, 5]) cuts at positions 2 and 5. All of these return new arrays.
Why we use it
Data often arrives in pieces, such as monthly files, separate feature arrays or batches. Stacking combines them into one array for analysis, and splitting cuts a big array into parts for batches, train and test sets or per-group work.
When to use it
Use vstack or concatenate(axis=0) to add rows, hstack or column_stack to add columns, split for equal chunks and array_split when sizes may not divide evenly. For tables with labels, pandas concat is the usual choice.
How it works
- Several arrays to combine
- Adding rows? Yes: vstack or concatenate(axis=0). No: hstack or concatenate(axis=1).
- Do the other dimensions match? Yes: Arrays are joined into one. No: ValueError: dimensions must match.
- Later, cut it again with np.split or np.array_split
- One combined array, or a list of pieces
Syntax
np.concatenate([a, b], axis=0)
np.vstack([a, b]) np.hstack([a, b])
np.column_stack([x1, x2])
np.split(a, n) np.split(a, [i, j]) np.array_split(a, n)Example
jan = np.array([[120, 135]])
feb = np.array([[90, 95]])
print(np.vstack([jan, feb]))Key points
- Pass the arrays as a list: np.vstack([a, b])
- All sizes must match except along the joining axis
- column_stack turns 1-D arrays into table columns
- np.split needs equal pieces; array_split does not
- Stacking copies data, so avoid stacking inside long loops