Sub topic 11
Reshaping and transposing
Reshaping and transposing change how an array's elements are arranged into axes. Most of the time they do this without copying any data. This chapter assumes you can create arrays and read shape, ndim, and dtype. It also assumes you know the view-versus-copy distinction from the earlier chapters. The last sections connect that distinction to strides.
Reshaping with reshape
reshape returns an array with the same elements and a new shape. The product of the new dimensions must equal size.
import numpy as np
a = np.arange(12)
b = a.reshape(3, 4)
print(b)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(b.base is a) # True: b is a view of a
b[0, 0] = 100
print(a[0]) # 100The new shape is a different description of the same buffer. Writing through b therefore changes a.
Letting NumPy infer one dimension
You can pass -1 for one dimension. NumPy computes it from the size and the other dimensions.
import numpy as np
a = np.arange(12)
print(a.reshape(2, -1).shape) # (2, 6)
print(a.reshape(-1, 3).shape) # (4, 3)
print(a.reshape(-1).shape) # (12,)
# a.reshape(-1, 5) raises ValueError, because 12 is not divisible by 5Only one -1 is allowed. This form is useful when the size is not known in advance, for example when you flatten the trailing axes of a batch.
Element order
reshape reads elements in C order by default. The last index varies fastest, so rows are filled first. Pass order="F" for Fortran order, where the first index varies fastest.
import numpy as np
a = np.arange(12)
print(a.reshape(3, 4, order="F"))
# [[ 0 3 6 9]
# [ 1 4 7 10]
# [ 2 5 8 11]]The order argument controls how the flat sequence is read and written. It does not change the buffer's physical layout.
Reshape is not transpose
A common mistake is to use reshape to swap rows and columns. reshape keeps the flat element order and regroups it. transpose changes which axis is which.
import numpy as np
a = np.arange(6).reshape(2, 3)
print(a.reshape(3, 2))
# [[0 1]
# [2 3]
# [4 5]]
print(a.T)
# [[0 3]
# [1 4]
# [2 5]]Both results have shape (3, 2), but the contents differ. Check values and not only shapes when you change layout.
Flattening: ravel, flatten, and reshape(-1)
Three tools produce a 1-D array. Their copy behavior differs.
| Tool | Result | Copies data? |
|---|---|---|
| `a.reshape(-1)` | 1-D array | Only if a view is impossible |
| `a.ravel()` | 1-D array | Only if a view is impossible |
| `a.flatten()` | 1-D array | Always |
Use flatten when you want an independent array. Otherwise ravel or reshape(-1) avoids an unneeded copy.
When reshape must copy
A view is possible only if the new shape can be described with strides over the existing buffer. A transposed array often fails this test.
import numpy as np
b = np.arange(12).reshape(3, 4)
t = b.T
flat = t.reshape(-1)
print(flat) # [ 0 4 8 1 5 9 2 6 10 3 7 11]
print(np.shares_memory(t, flat)) # False: reshape made a copy
print(np.shares_memory(b.reshape(-1), b)) # True: this one is a viewThe flat order of t is not the order of the elements in memory, so no single stride can walk them. reshape silently copies in this case.
The diagram summarizes the decision.
Adding and removing axes
Broadcasting often needs a length-1 axis. There are three ways to add one.
import numpy as np
v = np.array([1, 2, 3])
print(v[:, np.newaxis].shape) # (3, 1)
print(v[np.newaxis, :].shape) # (1, 3)
print(v.reshape(-1, 1).shape) # (3, 1)
print(np.expand_dims(v, 0).shape) # (1, 3)
print(v[:, np.newaxis] * v)
# [[1 2 3]
# [2 4 6]
# [3 6 9]]np.newaxis is an alias for None, so v[:, None] means the same thing. The reverse operation is np.squeeze, which removes axes of length 1.
import numpy as np
w = np.zeros((1, 3, 1))
print(w.squeeze().shape) # (3,)
print(w.squeeze(axis=0).shape) # (3, 1)Pass axis to squeeze when you know which axis to drop. A bare squeeze() can remove an axis that happens to have length 1 on a particular input, such as a batch of one. That changes the result's rank in ways that are hard to debug.
Transposing
For a 2-D array, .T swaps the two axes. For an n-D array, .T reverses the order of all axes. A 1-D array is unchanged, because it has only one axis.
import numpy as np
print(np.arange(3).T.shape) # (3,): no effect on 1-D
x = np.arange(24).reshape(2, 3, 4)
print(x.T.shape) # (4, 3, 2)
print(x.transpose(1, 0, 2).shape) # (3, 2, 4)
print(x.swapaxes(0, 2).shape) # (4, 3, 2)
print(np.moveaxis(x, 0, -1).shape) # (3, 4, 2)transpose(*axes)takes a full permutation. Entryiof the argument names the old axis that becomes new axisi.swapaxes(i, j)exchanges two axes and leaves the rest alone.moveaxis(source, destination)moves an axis and keeps the relative order of the others. It is usually clearer than a long permutation.
To turn a row vector into a column vector, use reshape(-1, 1) or [:, None]. .T does nothing on a 1-D array.
Why transposing is cheap
Every array carries strides, the number of bytes to step along each axis. Transposing permutes the shape and strides and leaves the data alone. This is the same mechanism that makes basic slices views. A common use is converting an image from height-width-channel order to channel-first order.
import numpy as np
img = np.zeros((32, 48, 3)) # float64, 8 bytes per element
chw = img.transpose(2, 0, 1)
print(chw.shape) # (3, 32, 48)
print(img.strides) # (1152, 24, 8)
print(chw.strides) # (8, 1152, 24)
print(np.shares_memory(img, chw)) # TrueNo pixel moved. The cost of the transposed layout appears later, because walking chw along its last axis jumps 24 bytes at a time. Operations that need contiguous memory, such as reshape(-1) on chw, copy the data. If you will reuse a transposed array many times, np.ascontiguousarray(chw) pays the copy once and makes later passes cache-friendly.
Common errors
- Size mismatch.
ValueError: cannot reshape array of size ...means the product of the dimensions does not equalsize. Printa.sizeand the target shape. - Wrong tool for swapping.
reshaperegroups elements and does not swap axes. Use.T,swapaxes, ormoveaxis. - Assuming a view. Writing into the result of
reshapeorravelmay or may not modify the original. Verify withnp.shares_memory. - Transposing a 1-D array. It returns the same shape. Add an axis instead.
- Overusing
squeeze(). Passaxisso the output rank does not depend on the data.
Exercise
Let a = np.arange(24).reshape(2, 3, 4) with dtype int64. What shape and strides does a.transpose(2, 0, 1) have, and does it copy data?
Show answer
The shape is (4, 2, 3). The original strides are (96, 32, 8) bytes, and transpose permutes them the same way as the shape, giving (8, 96, 32). No data is copied, so the result is a view that shares memory with a.
Exercise
You have x = np.array([1, 2, 3]) and want a (3, 1) column vector. Why does x.T fail to do this, and give two expressions that work.
Show answer
x is 1-D, so it has only one axis and .T returns it unchanged with shape (3,). Either x.reshape(-1, 1) or x[:, np.newaxis] gives shape (3, 1).
Exercise
b = np.arange(12).reshape(3, 4). Does b.T.reshape(-1) share memory with b? Explain.
Show answer
No. The transposed array is not C-contiguous, so no single stride can walk its elements in flat C order. reshape must copy, and np.shares_memory(b, b.T.reshape(-1)) returns False.