Data often arrives in pieces: January's sales in one array and February's in another, features in one table and labels in another, or a dataset you need to cut into training and test parts. NumPy has a small family of functions to join arrays together and split them apart.
This lesson explains concatenate, vstack, hstack, stack, split and array_split, and the idea that makes them all click: the axis.
First, what is an axis?
An axis is a direction in an array. In a 2D table:
- axis 0 runs down the rows. Joining along axis 0 adds more rows.
- axis 1 runs across the columns. Joining along axis 1 adds more columns.
Keep that picture in mind and every function below makes sense.
concatenate: join along an existing axis
np.concatenate takes a list of arrays and joins them end to end:
import numpy as np
jan = np.array([120, 135, 128])
feb = np.array([140, 150])
print(np.concatenate([jan, feb])) # [120 135 128 140 150]
For 2D arrays, choose the axis:
a = np.array([[1, 2],
[3, 4]])
b = np.array([[5, 6]])
print(np.concatenate([a, b], axis=0)) # add b as a new row
[[1 2]
[3 4]
[5 6]]
c = np.array([[7],
[8]])
print(np.concatenate([a, c], axis=1)) # add c as a new column
[[1 2 7]
[3 4 8]]
The arrays must match on every axis except the one you join along. Adding a row of 3 values to a table with 2 columns fails:
ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 2 and the array at index 1 has size 3
Read the message: it tells you which dimension and which array don't match.
vstack and hstack: the readable shortcuts
np.vstack stacks vertically (more rows) and np.hstack stacks horizontally (more columns):
print(np.vstack([a, b])) # same as concatenate axis=0
print(np.hstack([a, c])) # same as concatenate axis=1
They're also friendlier with 1D arrays. vstack treats each 1D array as a row, which is a neat way to build a table:
maths = np.array([72, 85, 91])
science = np.array([80, 78, 95])
print(np.vstack([maths, science]))
[[72 85 91]
[80 78 95]]
To put them side by side as columns instead, use np.column_stack:
print(np.column_stack([maths, science]))
[[72 80]
[85 78]
[91 95]]
That's the shape scikit-learn wants: one row per student, one column per feature.
stack: join along a new axis
concatenate makes an existing axis longer. np.stack creates a new axis, so the arrays must all have exactly the same shape:
print(np.stack([maths, science]).shape) # (2, 3)
print(np.stack([maths, science], axis=1).shape) # (3, 2)
The classic use is turning a list of same-sized images into one batch:
images = [np.zeros((28, 28)) for _ in range(32)]
batch = np.stack(images)
print(batch.shape) # (32, 28, 28)
| Function | Joins along | Shapes must match |
|---|---|---|
concatenate | An existing axis you choose | Except along that axis |
vstack | Rows (axis 0) | Same number of columns |
hstack | Columns (axis 1 for 2D) | Same number of rows |
column_stack | 1D arrays become columns | Same length |
stack | A brand new axis | Exactly |
split: cut an array into equal parts
np.split(array, n) cuts into n equal pieces and returns a list:
data = np.arange(12)
parts = np.split(data, 3)
print(parts)
[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])]
If the array can't be divided equally, split raises an error. np.array_split allows unequal parts:
for part in np.array_split(np.arange(10), 3):
print(part)
[0 1 2 3]
[4 5 6]
[7 8 9]
You can also give the positions to cut at, which is how you'd split data into training and test sets by hand:
train, test = np.split(data, [9])
print(train) # [0 1 2 3 4 5 6 7 8]
print(test) # [ 9 10 11]
In real projects, shuffle the data first, or use scikit-learn's train_test_split, which shuffles for you.
np.vsplit and np.hsplit split 2D arrays into groups of rows and groups of columns, mirroring vstack and hstack.
A performance tip
Each call to concatenate builds a brand new array and copies everything into it. Calling it inside a loop, adding one row at a time, gets slow fast. Collect the pieces in a Python list instead, then join once at the end:
rows = []
for day in range(5):
rows.append(np.array([day, day * 10]))
table = np.vstack(rows)
print(table.shape) # (5, 2)
Practice
- Join
np.array([1, 2, 3])andnp.array([4, 5]), then split the result into 2 parts that are as equal as possible.
Show the answer
joined = np.concatenate([np.array([1, 2, 3]), np.array([4, 5])])
print(np.array_split(joined, 2))
# [array([1, 2, 3]), array([4, 5])]
np.split(joined, 2) would fail because 5 values can't be split equally.
- You have
Xof shape(100, 3)andextraof shape(100,). Addextraas a fourth column.
Show the answer
X = np.zeros((100, 3))
extra = np.ones(100)
X2 = np.column_stack([X, extra])
print(X2.shape) # (100, 4)
np.hstack([X, extra.reshape(-1, 1)]) also works.
- What is the shape of
np.stack([np.zeros((2, 3))] * 4, axis=2)?
Show the answer
(2, 3, 4). The new axis of length 4 is inserted at position 2, the end.
Interview questions
What is the difference between np.concatenate and np.stack?
concatenate joins arrays along an existing axis, making it longer, so the arrays need to match on all other axes. stack adds a new axis and needs all arrays to have identical shapes; stacking four (2, 3) arrays gives (4, 2, 3).
What is the difference between np.split and np.array_split?
split requires the array to divide into exactly equal parts and raises an error otherwise. array_split allows parts that differ in size by one.
Why shouldn't you call np.append or np.concatenate inside a loop?
Each call allocates a new array and copies all existing data, so building an array of n rows this way is O(n²). Append to a Python list and join once at the end, or preallocate with np.zeros and fill it.
What to learn next
- Learn when arrays share memory in NumPy copy vs view.
- Join labelled tables with pandas in the pandas DataFrame tutorial.