NumPy Shapes: reshape, transpose, stack, concatenate and split
Change the shape of a NumPy array without changing its data: reshape and -1, transpose, newaxis and squeeze, then stack, concatenate and split, with the errors you get when shapes don't fit.
What you will learn
- Reshape an array, use -1 to let NumPy work out a size, and read the reshape error
- Tell reshape from transpose, and ravel from flatten
- Add and remove dimensions with np.newaxis and squeeze
- Join arrays with stack and concatenate, and cut them with split and array_split
Before you start
- NumPy arrays, shape and dtype
- NumPy indexing and slicing
Data doesn't always arrive in the shape you need. A model wants a column and you have a line. Two days of readings need to become one table. A dataset has to be cut into training and test rows. So in this lesson, shape is the whole story.
Think about twelve numbered chairs standing in one long line. You take them in order and make three rows of four. Need a wider room? Same chairs, two rows of six. You didn't add or remove a chair, you only moved them. Five rows of three would need fifteen chairs, so that can't be done. That's reshaping: the data stays the same, only the arrangement changes.
reshape: a new shape, the same data
import numpy as np
arr = np.arange(12)
print(arr)
print(arr.shape)
grid = arr.reshape(3, 4)
print(grid)
print(grid.shape)
[ 0 1 2 3 4 5 6 7 8 9 10 11]
(12,)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
(3, 4)
The values fill the first row left to right, then the second, then the third, like reading a page. Twelve values before, twelve after. With the values 1 to 6, reshape(2, 3), (3, 2), (1, 6) and (6, 1) all work, because each pair multiplies to six. That's the only rule. Note that (1, 6) prints with double brackets: one row, but still two dimensions.
-1: let NumPy work it out
arr = np.arange(12)
print(arr.reshape(2, -1).shape)
print(arr.reshape(-1, 3).shape)
print(arr.reshape(-1, 2, 3).shape)
print(arr.reshape(-1).shape)
(2, 6)
(4, 3)
(2, 2, 3)
(12,)
-1 means "you work this one out". Fix the sizes you care about and leave one to NumPy. reshape(-1) on its own lays everything out in one line.
When the shape doesn't fit
arr = np.arange(12)
print(arr.size)
bad = arr.reshape(5, 3)
print(bad)
12
Traceback (most recent call last):
File "S05L03_Shape\reshape_error.py", line 6, in <module>
bad = arr.reshape(5, 3)
ValueError: cannot reshape array of size 12 into shape (5,3)
The message gives you both numbers. Multiply your shape and compare it with the size.
ravel and flatten
grid = np.arange(6).reshape(2, 3)
print(grid.ravel())
print(grid.flatten())
print(np.shares_memory(grid, grid.ravel()))
print(np.shares_memory(grid, grid.flatten()))
[0 1 2 3 4 5]
[0 1 2 3 4 5]
True
False
Both give one line. Here ravel is a view on the same data, and flatten always makes a separate copy. Use ravel to read, flatten when you want your own copy to change.
Transpose: swapping the axes
Reshaping keeps the reading order. Transposing is different: it swaps the axes, so rows become columns.
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.shape)
print(m.T)
print(m.T.shape)
print(np.transpose(m))
print(np.shares_memory(m, m.T))
(2, 3)
[[1 4]
[2 5]
[3 6]]
(3, 2)
[[1 4]
[2 5]
[3 6]]
True
m.T is the short form of np.transpose(m), and it's a view, so no data is copied. With more dimensions it's the same idea. A cube of shape (2, 3, 4) gives (4, 3, 2) with .T, which reverses all the axes. np.transpose(cube, (1, 0, 2)) lets you choose the order and gives (3, 2, 4), and np.swapaxes(cube, 0, 2) exchanges just two axes, giving (4, 3, 2).
Adding and removing a dimension
v = np.array([10, 20, 30])
print(v.shape)
row = v[np.newaxis, :]
col = v[:, np.newaxis]
print(row.shape)
print(row)
print(col.shape)
print(col)
print(np.expand_dims(v, axis=1).shape)
(3,)
(1, 3)
[[10 20 30]]
(3, 1)
[[10]
[20]
[30]]
(3, 1)
np.newaxis adds a dimension of size one wherever you put it: in front gives one row, after gives one column. np.expand_dims does the same by axis number. The opposite is np.squeeze, which removes dimensions of size one:
x = np.array([[[1, 2, 3]]])
print(x.shape)
print(np.squeeze(x).shape)
col = np.array([[10], [20], [30]])
print(col.shape)
print(np.squeeze(col, axis=1).shape)
print(col.reshape(-1).shape)
(1, 1, 3)
(3,)
(3, 1)
(3,)
(3,)
Why shapes matter
Many calculations only work when the shapes fit. Matrix multiplication is everywhere in AI, and in Python you write it with @.
a = np.arange(6).reshape(2, 3)
b = np.arange(6, 12).reshape(2, 3)
print(a.shape, b.shape)
print(a @ b)
(2, 3) (2, 3)
Traceback (most recent call last):
File "S05L03_Shape\matmul_error.py", line 7, in <module>
print(a @ b)
~~^~~
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)
Put the shapes side by side: the two inner numbers must match, and here it's 3 against 2. Transpose b and it works:
print(a.shape, b.T.shape)
print(a @ b.T)
(2, 3) (3, 2)
[[ 23 32]
[ 86 122]]
The first row of a meets the first column of b.T: 0×6 + 1×7 + 2×8 = 23. The outer numbers give the result shape, 2 by 2. A lot of shape work is really this: getting arrays ready so the calculation can happen. Linear algebra with NumPy goes further.
Joining arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.vstack((a, b)))
print(np.hstack((a, b)))
print(np.column_stack((a, b)))
[[1 2 3]
[4 5 6]]
[1 2 3 4 5 6]
[[1 4]
[2 5]
[3 6]]
vstack puts them on top of each other as rows, hstack joins them end to end, and column_stack stands each one up as a column. Plain np.stack creates a new axis for them to sit along: by default it goes first (shape (2, 3)), and with axis=1 it goes second (shape (3, 2), same values as column_stack).
concatenate joins along an axis you already have
x = np.array([[1, 2], [3, 4]])
y = np.array([[5, 6], [7, 8]])
print(np.concatenate((x, y), axis=0))
print(np.concatenate((x, y), axis=1))
[[1 2]
[3 4]
[5 6]
[7 8]]
[[1 2 5 6]
[3 4 7 8]]
Axis 0 adds rows, axis 1 adds columns. The pieces have to fit, though. With x of shape (2, 2) and y of shape (3, 2):
x = np.ones((2, 2), dtype=int)
y = np.ones((3, 2), dtype=int)
print(np.concatenate((x, y), axis=0).shape)
print(np.concatenate((x, y), axis=1).shape)
(5, 2)
Traceback (most recent call last):
File "S05L03_Shape\concatenate_error.py", line 7, in <module>
print(np.concatenate((x, y), axis=1).shape)
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
ValueError: all the input array dimensions except for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 1 has size 3
Every axis has to match except the one you're joining along.
Splitting arrays
arr = np.arange(12)
a, b, c = np.split(arr, 3)
print(a)
print(b)
print(c)
[0 1 2 3]
[4 5 6 7]
[ 8 9 10 11]
np.split(arr, 5) fails with ValueError: array split does not result in an equal division, because twelve doesn't divide by five. When close enough is fine, use np.array_split:
for part in np.array_split(arr, 5):
print(part)
[0 1 2]
[3 4 5]
[6 7]
[8 9]
[10 11]
The two leftover values go to the first two parts. You can also say exactly where to cut by passing a list:
first, middle, last = np.split(arr, [3, 7])
print(first)
print(middle)
print(last)
[0 1 2]
[3 4 5 6]
[ 7 8 9 10 11]
A single number means how many parts. A list means where to cut. On a grid, np.vsplit cuts across the rows (shorter grids) and np.hsplit cuts down the columns (narrower grids).
Three jobs you'll meet in practice
A feature column. Machine learning tools usually want a table, one row per sample and one column per feature:
prices = np.array([200, 350, 500, 150])
print(prices.shape)
X = prices.reshape(-1, 1)
print(X.shape)
print(X)
(4,)
(4, 1)
[[200]
[350]
[500]
[150]]
Stacking datasets. Two days of three temperature readings each become one table:
day1 = np.array([22.1, 23.4, 21.8])
day2 = np.array([24.0, 25.2, 23.5])
all_days = np.vstack((day1, day2))
print(all_days)
print(all_days.shape)
[[22.1 23.4 21.8]
[24. 25.2 23.5]]
(2, 3)
A train and test split. Hold back some rows for testing:
data = np.arange(500).reshape(100, 5)
train, test = np.split(data, [80])
print(train.shape)
print(test.shape)
print(test[0])
(80, 5)
(20, 5)
[400 401 402 403 404]
The first test row starts at 400 because 80 rows of 5 values come before it. In real projects you'd shuffle first; see train/test split and data leakage.
Recap
| Tool | What it does |
|---|---|
reshape, -1 | New shape, same data in reading order; -1 works out one size |
ravel / flatten | One line; ravel can be a view, flatten is always a copy |
.T, transpose, swapaxes | Swap the axes (a view) |
np.newaxis, squeeze | Add or remove a dimension of size one |
vstack, hstack, stack, concatenate | Join; stack makes a new axis, concatenate uses an existing one |
split, array_split, vsplit, hsplit | Cut into equal parts, near-equal parts, or at positions |
Try it yourself: reshape 24 values to 4 by 6, split the rows into two parts and stack them back. Or ask an AI tool to write it, then check every shape it prints.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
