Skip to main content
Albero Academy

Combining & Splitting Arrays

Join arrays with concatenate, stack and hstack/vstack, split them back apart, and tile or repeat to build larger arrays.

Chapter 5NumPy14 min readBeginner friendly
  • #NumPy
  • #Stacking
  • #Concatenate

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:

joining along an axis
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
np.concatenate([a, b], axis=0) # stack rows → 3×2
np.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):

vstack, hstack, stack
np.vstack([a, b]) # vertical (rows) → like concatenate axis=0
np.hstack([a, a]) # horizontal (cols) → like concatenate axis=1
np.column_stack([[1,2],[3,4]]) # 1-D arrays as columns
imgs = 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:

cutting arrays apart
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:

two kinds of repetition
np.tile([1, 2], 3) # [1 2 1 2 1 2] whole pattern repeated
np.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

  1. 01np.concatenate joins arrays along an existing axis; shapes must match except on that axis.
  2. 02vstack/hstack are readable shorthands; np.stack adds a new axis (e.g. batching images).
  3. 03hsplit/vsplit/array_split cut arrays apart; array_split tolerates uneven splits.
  4. 04tile repeats the whole block; repeat repeats each element.
  5. 05Choose the axis deliberately — it decides whether you grow rows or columns.