Reshaping in Python
Same buffer, different shape — as long as the sizes agree.
import numpy as np
values = np.arange(12)
grid = values.reshape(3, 4)
print(grid)
print(grid.reshape(2, -1).shape, grid.T.shape)
print(grid.ravel()[:5])
view = grid.reshape(-1)
view[0] = 99
print(grid[0, 0], values[0])
How it works
-1lets numpy work one dimension out for you.ravelflattens;Ttransposes without copying.reshapereturns a view when it can, so writes show through.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 12
- Characters to type
- 221
- Tokens
- 87
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 50 seconds.
Step 2 of 4 in Types & shapes, step 10 of 22 in NumPy.