Sub topic 11
Reshaping and transposing
This chapter assumes you can create arrays, read shape, and tell views from copies. Reshaping and transposing change how an array's elements are arranged into dimensions. They leave the values themselves unchanged.
Reshaping
reshape returns an array with the same elements in a new shape. The total number of elements must stay the same. Elements are read in row-major (C) order, so the last axis varies fastest.
import numpy as np
a = np.arange(6).reshape(2, 3)
b = a.reshape(3, 2)
print(b)
# [[0 1]
# [2 3]
# [4 5]]
print(np.shares_memory(a, b)) # True
b[0, 0] = 99
print(a[0, 0]) # 99Here b is a view of a, so writing to b changes a. Pass -1 for one dimension and NumPy infers it from the others. Only one -1 is allowed. A shape whose product does not equal the array's size raises ValueError.
ravel() flattens to 1-D and returns a view when it can. flatten() always returns a copy.
Transposing
a.T swaps the axes. For arrays with more than two dimensions, transpose takes the new axis order. Both return views with rearranged strides, so no data moves.
import numpy as np
a = np.arange(6).reshape(2, 3)
print(a.T.shape) # (3, 2)
x = np.zeros((2, 3, 4))
print(x.transpose(2, 0, 1).shape) # (4, 2, 3)In transpose(2, 0, 1), the new axis 0 is the old axis 2, the new axis 1 is the old axis 0, and so on.
Reshaping after a transpose
A transposed array is no longer contiguous in memory. reshape cannot always express the new shape as a view of that layout, so it quietly makes a copy.
import numpy as np
a = np.arange(6).reshape(2, 3)
t = a.T
flat = t.reshape(6)
print(flat) # [0 3 1 4 2 5]
print(np.shares_memory(a, flat)) # FalseThe elements come out in the transposed order, and flat owns its own data. Writing to flat does not change a. You get a view or a copy depending on the layout, so don't write code that relies on either one.
Adding axes
Reshaping is also the usual way to prepare arrays for broadcasting.
import numpy as np
v = np.array([1, 2, 3])
print(v.reshape(1, -1).shape) # (1, 3), row vector
print(v[:, np.newaxis].shape) # (3, 1), column vectorCommon errors
- Size mismatch.
np.arange(6).reshape(4, -1)fails because 6 is not divisible by 4. - Assuming a view. After a transpose,
reshapemay copy, so a write may not reach the original array. - Confusing reshape with transpose.
reshape(3, 2)and.Tboth give shape(3, 2)from(2, 3), but they place elements differently. Reshape keeps the row-major reading order. Transpose swaps rows and columns.
Exercise
Given a = np.arange(12).reshape(3, 4), what is the shape of a.T.reshape(2, -1), and does the result share memory with a?
Show answer
The shape is (2, 6). a.T has shape (4, 3) and is not contiguous, so reshape has to copy the elements. The result does not share memory with a.