NumPy: Concatenation and Splitting

Last updated: 2026-08-26

Concatenation and Splitting

1. What You'll Learn



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.

PYTHON
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]]
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(2) vstack and hstack

PYTHON
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)
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(3) stack — Join with a New Dimension

stack creates a new axis and joins along it:

PYTHON
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]]
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(4) split — Splitting Arrays

PYTHON
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
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.

(5) repeat and tile

PYTHON
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)
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.


▶ Example

TEXT 📖 Display only
> **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 ⭐)

PYTHON
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]
TEXT 📖 Display only
> **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.
⚠️ Note: The code below needs to run in a local Python environment.



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 ⭐⭐)

PYTHON
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 only
Part 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 ⭐)

PYTHON
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 only
repeat: [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

Q What's the difference between concatenate and stack?
A concatenate joins existing arrays along an existing axis — no new dimensions. stack creates a new axis and joins along it, adding one dimension.
Q Can I concatenate arrays of different shapes?
A They must match in all dimensions except the join axis. For example, to concatenate along axis 0, the arrays must have the same number of columns.
Q What happens if I split an array into unequal parts?
A np.split requires equal divisions — it raises an error. Use np.array_split for unequal splits, which handles the remainder gracefully.

📖 Summary



📝 Exercises

  1. Beginner (Difficulty ⭐): Create two 3x4 arrays of random numbers. Concatenate them along axis 0, then along axis 1. Print the shapes of the results.

  2. Intermediate (Difficulty ⭐⭐): Create three 1D arrays of length 5. Use stack to combine them into a 3x5 array. Then use vstack and compare the shapes.

  3. Advanced (Difficulty ⭐⭐⭐): Create a 12x8 array. Split it into 3 equal parts, then split it at indices [3, 7]. Use np.tile to repeat a 2x2 pattern into an 8x8 grid.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏