Skip to main content
Albero Academy

Reshaping

Change an array's shape with reshape, ravel, transpose and newaxis.

Manipulation9 min

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

reshape & -1
a = np.arange(12) # [0 1 … 11]
a.reshape(3, 4) # 3 rows × 4 cols
a.reshape(4, -1) # -1 = "infer this dimension" → 4×3
a.ravel() # flatten back to 1-D

Transpose

.T swaps axes
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:

newaxis
v = np.array([1, 2, 3])
v[:, None].shape # (3, 1) — a column
v[None, :].shape # (1, 3) — a row

Key takeaways

  1. 01reshape rearranges elements into a new shape with the same total size; -1 infers a dimension.
  2. 02ravel flattens to 1-D; .T transposes (swaps axes).
  3. 03np.newaxis / None inserts a length-1 axis — the trick to make shapes broadcast.
  4. 04Reshaping keeps the element count constant; a mismatch errors.

Finished this chapter?

Mark it complete to track your progress through NumPy.