NumPy: Concatenation and Splitting
Last updated: 2026-08-26
Concatenation and Splitting
1. What You'll Learn
- ❶ concatenate — joining along an axis
- ❷ vstack / hstack — convenience functions
- ❸ stack — joining with a new dimension
- ❹ split / vsplit / hsplit — splitting arrays
- ❺ repeat / tile — repeating and expanding
2. A Developer's True Story
(1) The Problem
Alice has 3 months of sales data, each month as a 4×3 array (4 products × 3 regions). She wants to merge them into one big table but keeps mixing up which axis to use with concatenate.
(2) The Solution
Bob draws a diagram: "Along axis 0, rows increase; along axis 1, columns increase." concatenate(axis=0) stacks vertically, concatenate(axis=1) stacks horizontally.
(3) The Payoff
After mastering concatenation and splitting, Alice can merge monthly data with one command, split by quarter, and use tile to expand prediction templates — 10x improvement in data assembly efficiency.
3. Key Concepts
(1) np.concatenate — Join Along an Axis
np.concatenate is the most general joining function, with the axis parameter controlling the direction.
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.array([[7, 8, 9],
[10, 11, 12]])
# Along axis 0: stack vertically (rows increase)
c0 = np.concatenate([a, b], axis=0)
# [[ 1 2 3]
# [ 4 5 6]
# [ 7 8 9]
# [10 11 12]]
# Along axis 1: stack horizontally (columns increase)
c1 = np.concatenate([a, b], axis=1)
# [[ 1 2 3 7 8 9]
# [ 4 5 6 10 11 12]]
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(2) vstack and hstack
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[5, 6],
[7, 8]])
# vstack: same as concatenate(axis=0)
v = np.vstack([a, b])
print(v.shape) # (4, 2)
# hstack: same as concatenate(axis=1)
h = np.hstack([a, b])
print(h.shape) # (2, 4)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(3) stack — Join with a New Dimension
stack creates a new axis and joins along it:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.array([7, 8, 9])
s = np.stack([a, b, c])
print(s.shape) # (3, 3)
print(s)
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(4) split — Splitting Arrays
import numpy as np
a = np.arange(12).reshape(6, 2)
# Split into 3 equal parts
parts = np.split(a, 3)
print(len(parts)) # 3
print(parts[0].shape) # (2, 2)
print(parts[1].shape) # (2, 2)
print(parts[2].shape) # (2, 2)
# Split at specific indices
parts2 = np.split(a, [2, 4])
print([p.shape for p in parts2]) # [(2,2), (2,2), (2,2)]
# vsplit: split along axis 0 (vertical)
# hsplit: split along axis 1 (horizontal)
v = np.vsplit(a, 3) # same as split(a, 3, axis=0)
h = np.hsplit(a, 2) # split columns
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
(5) repeat and tile
import numpy as np
a = np.array([1, 2, 3])
# repeat: repeat each element
print(np.repeat(a, 3)) # [1 1 1 2 2 2 3 3 3]
# tile: repeat the entire array
print(np.tile(a, 3)) # [1 2 3 1 2 3 1 2 3]
# 2D tile
b = np.array([[1, 2], [3, 4]])
print(np.tile(b, (2, 3)).shape) # (4, 6)
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
▶ Example
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
: Concatenation vs stacking (Difficulty ⭐)
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print("concatenate:", np.concatenate([a, b]))
# [1 2 3 4 5 6]
print("stack:", np.stack([a, b]))
# [[1 2 3]
# [4 5 6]]
print("vstack:", np.vstack([a, b]))
# [[1 2 3]
# [4 5 6]]
print("hstack:", np.hstack([a, b]))
# [1 2 3 4 5 6]
> **Output:** Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.
4. Comparison Tables
(1) Concatenation Methods
| Function | axis | Shape Requirement | Result Shape Change |
|---|---|---|---|
concatenate |
specified | Same except join axis | Join axis sums |
vstack |
0 | Same # of columns | Rows increase |
hstack |
1 | Same # of rows | Columns increase |
stack |
new axis | Same shape entirely | New dimension added |
(2) repeat vs tile
| Function | Behavior | Example |
|---|---|---|
repeat(3) |
Repeat each element 3x | [1,2] → [1,1,1,2,2,2] |
tile(3) |
Repeat the whole array 3x | [1,2] → [1,2,1,2,1,2] |
▶ Example: Using array_split for uneven splits (Difficulty ⭐⭐)
import numpy as np
a = np.arange(10)
# split requires equal parts — raises error for 3 parts
# array_split handles uneven splits gracefully
parts = np.array_split(a, 3)
for i, p in enumerate(parts):
print(f"Part {i}: shape={p.shape}, values={p}")
# 2D array_split
b = np.arange(20).reshape(5, 4)
parts_2d = np.array_split(b, 3)
for i, p in enumerate(parts_2d):
print(f"2D Part {i}: shape={p.shape}")
Output:
TEXT 📖 Display onlyPart 0: shape=(4,), values=[0 1 2 3] Part 1: shape=(3,), values=[4 5 6] Part 2: shape=(3,), values=[7 8 9] 2D Part 0: shape=(2, 4) 2D Part 1: shape=(2, 4) 2D Part 2: shape=(1, 4)
▶ Example: repeat and tile for data expansion (Difficulty ⭐)
import numpy as np
a = np.array([1, 2, 3])
# repeat: repeat each element individually
print("repeat:", np.repeat(a, 3))
# tile: repeat the entire array
print("tile:", np.tile(a, 3))
# Practical: expand a pattern
pattern = np.array([[1, 0], [0, 1]])
grid = np.tile(pattern, (2, 3))
print("Tiled pattern:\n", grid)
print("Shape:", grid.shape)
Output:
TEXT 📖 Display onlyrepeat: [1 1 1 2 2 2 3 3 3] tile: [1 2 3 1 2 3 1 2 3] Tiled pattern: [[1 0 1 0 1 0] [0 1 0 1 0 1] [1 0 1 0 1 0] [0 1 0 1 0 1]] Shape: (4, 6)
❓ FAQ
📖 Summary
concatenatejoins along an existing axis; axes must match except the join axisvstack/hstackare shortcuts for axis 0 and axis 1 concatenationstackcreates a new dimension, useful for building batches of datasplit/vsplit/hsplitdivide arrays into equal parts or at specific indicesrepeatrepeats elements;tilerepeats the whole array
📝 Exercises
-
Beginner (Difficulty ⭐): Create two 3x4 arrays of random numbers. Concatenate them along axis 0, then along axis 1. Print the shapes of the results.
-
Intermediate (Difficulty ⭐⭐): Create three 1D arrays of length 5. Use
stackto combine them into a 3x5 array. Then usevstackand compare the shapes. -
Advanced (Difficulty ⭐⭐⭐): Create a 12x8 array. Split it into 3 equal parts, then split it at indices [3, 7]. Use
np.tileto repeat a 2x2 pattern into an 8x8 grid.