The same data can be viewed in different shapes. Reshaping rearranges how elements are laid out logically without changing the values — essential for feeding data into functions that expect a particular shape.
reshape
a = np.arange(12) # [0 1 … 11]a.reshape(3, 4) # 3 rows × 4 colsa.reshape(4, -1) # -1 = "infer this dimension" → 4×3a.ravel() # flatten back to 1-D
Transpose
m = np.array([[1, 2, 3], [4, 5, 6]]) # (2, 3)m.T # (3, 2) — rows become columns
Adding an axis
np.newaxis (or None) inserts a length-1 dimension — the key to making shapes broadcast:
v = np.array([1, 2, 3])v[:, None].shape # (3, 1) — a columnv[None, :].shape # (1, 3) — a row
Key takeaways
- 01reshape rearranges elements into a new shape with the same total size; -1 infers a dimension.
- 02ravel flattens to 1-D; .T transposes (swaps axes).
- 03np.newaxis / None inserts a length-1 axis — the trick to make shapes broadcast.
- 04Reshaping keeps the element count constant; a mismatch errors.
