Real data rarely arrives as one tidy array — you assemble it from pieces (batches of rows, columns of features) and split it back for processing. This chapter is the joinery: putting arrays together along an axis and cutting them apart again.
Concatenate
np.concatenate is the general tool — it glues arrays along an existing axis. The arrays must match in every dimension except the one you join on:
a = np.array([[1, 2], [3, 4]])b = np.array([[5, 6]])np.concatenate([a, b], axis=0) # stack rows → 3×2np.concatenate([a, a], axis=1) # widen columns → 2×4
Stacking
vstack/hstack are readable shorthands, and np.stack creates a new axis (turning a list of 2-D arrays into a 3-D one — how you build image batches):
np.vstack([a, b]) # vertical (rows) → like concatenate axis=0np.hstack([a, a]) # horizontal (cols) → like concatenate axis=1np.column_stack([[1,2],[3,4]]) # 1-D arrays as columnsimgs = np.stack([img1, img2, img3]) # new leading axis → shape (3, H, W)
Splitting
The inverse of stacking. Split into equal parts, or at explicit indices:
a = np.arange(12).reshape(3, 4)np.hsplit(a, 2) # two 3×2 halves (split columns)np.vsplit(a, 3) # three 1×4 rows (split rows)np.array_split(a, 2, axis=0) # handles uneven splits without error
Tile & repeat
Build a bigger array by repeating a smaller one. tile repeats the whole block; repeat repeats each element:
np.tile([1, 2], 3) # [1 2 1 2 1 2] whole pattern repeatednp.repeat([1, 2], 3) # [1 1 1 2 2 2] each element repeated
Practice
Build a 6×2 array by vstacking three 2×2 blocks, then hsplit a 4×4 array into two halves. Use np.stack to combine three same-shaped 2-D arrays into one 3-D array and confirm its shape. Contrast tile and repeat on the same input.
Key takeaways
- 01np.concatenate joins arrays along an existing axis; shapes must match except on that axis.
- 02vstack/hstack are readable shorthands; np.stack adds a new axis (e.g. batching images).
- 03hsplit/vsplit/array_split cut arrays apart; array_split tolerates uneven splits.
- 04tile repeats the whole block; repeat repeats each element.
- 05Choose the axis deliberately — it decides whether you grow rows or columns.
