NumPy·Lesson 10·10 min·0/3 exercises

Reshaping and transposing

The memory never moves — only the rule for walking it.

.reshape-1.ravel.flatten.Tnp.newaxis.transpose

Watch it happen

Play it through, or step back and forth yourself.

np.arange(12)
0
1
2
3
4
5
6
7
8
9
10
11
0
1
2
3
4
5
6
7
8
9
10
11
shape (12,)
memory — identical at every step above
0
1
2
3
4
5
6
7
8
9
10
11

Start with np.arange(12) — a flat run of twelve values. In memory this is one straight line, and it stays one straight line for this entire lesson.

The idea

Reshaping feels like rearranging data. It isn't. The twelve numbers stay exactly where they were, in exactly the order they were in — reshape changes only where the line gets broken as it's read back.

NumPy fills the last axis fastest: across a row, then down to the next. That's C order, and it's why np.arange(12).reshape(3, 4) puts 0 1 2 3 in the first row.

The product of the new shape has to match the number of elements. 12 can become (3, 4), (4, 3), (2, 6) or (2, 2, 3), but not (5, 3) — and NumPy raises rather than guessing.

Letting NumPy do the arithmetic

Put -1 in one position and NumPy works it out: a.reshape(3, -1) means "three rows, however many columns that needs". Only one -1 per call, for the obvious reason.

Flattening is the same idea in reverse. a.ravel() gives a 1-D view when it can; a.flatten() always copies. Prefer ravel unless you plan to modify the result.

Transpose is not reshape

a.reshape(4, 3) and a.T both produce a (4, 3) array, and they hold different values in different places. Reshape re-reads memory in the same order. Transpose swaps the axes, so it walks down-then-across instead.

Remarkably, transpose still doesn't copy. NumPy tracks a stride per axis — how many bytes to jump to reach the next element along it — and transposing just swaps the strides. Same memory, new reading rule.

Adding an axis

You'll often need a (3,) to behave as a (3, 1) so it broadcasts down a column instead of across a row (next lesson). Three ways to say it:

v[:, np.newaxis]   # (4,) -> (4, 1)
v[:, None]         # identical, np.newaxis IS None
v.reshape(-1, 1)   # same result

Practice

Write it yourself. The answer is there when you want it.

Putting the kettle on…

Starting up…

Write it yourself

not graded

Make np.arange(12) and print it as a (3, 4). Show that -1 works the missing dimension out for you. Then print reshape(4, 3) and reshape(3, 4).T one after the other — same shape, different contents, and it matters. Finish with the shape of v[:, None].

Write something and press Run — the output appears here.

Your turn

3 exercises. Write the code yourself, then press Check — a nudge and the answer are there if you want them.

Reshape a into 2 rows, letting NumPy work out the columns.

your answer

Return cups transposed, so stalls run down and days run across.

your answer

Turn v from shape (4,) into a column of shape (4, 1).

your answer