Transpose, .T & swapaxes
Flip rows and columns with .T and np.transpose, reorder axes of 3D data, and swap two axes with swapaxes — plus why you would transpose data at all.
Watch the lesson
1 video on CodeWithMunnaX
Our squad table is players × matches: each row is a player. But a match-day analyst wants to read it match by match — "show me everyone's score in match 3". Instead of rebuilding the data, you just flip it so matches become rows. That flip is the transpose.
Definition
Transposing an array reverses (or reorders) its axes. For a 2D array this means rows become columns and columns become rows: an array of shape
(r, c)becomes(c, r), and the element at[i, j]moves to[j, i]. The data itself does not change, and the result is a view.
- Flip across the diagonal — the main diagonal (
[0,0],[1,1], …) stays put; everything else mirrors across it. [i, j] → [j, i]— Rohit's match-3 score isscores[1, 2]; in the transpose it isT[2, 1].- View — no data is copied; NumPy just reads the same memory in a different order.
text
Original (players × matches), shape (3, 4): Transposed (matches × players), shape (4, 3):
M1 M2 M3 M4 Virat Rohit Hardik
Virat [ 72 45 88 31 ] M1 [ 72 56 45 ]
Rohit [ 56 0 74 88 ] M2 [ 45 0 32 ]
Hardik [ 45 32 0 67 ] M3 [ 88 74 0 ]
M4 [ 31 88 67 ]Syntax
python
a.T # attribute (no brackets) — reverses all axes
a.transpose() # method — same as a.T
np.transpose(a, axes=None) # function; axes lets you choose the new order
a.transpose(2, 0, 1) # e.g. 3D: new axis 0 = old axis 2, ...
np.swapaxes(a, axis1, axis2) # swap exactly two axes
a.swapaxes(axis1, axis2)
np.moveaxis(a, source, destination) # move one axis to a new position| Parameter | Meaning | Default |
|---|---|---|
a | input array | — required |
axes | a tuple giving the new order of the old axes, e.g. (1, 0) or (2, 0, 1) | None = reverse all axes |
axis1, axis2 | (swapaxes) the two axes to exchange | — required |
source, destination | (moveaxis) where the axis is now, and where it should go | — required |
Example — players × matches → matches × players
python
import numpy as np
scores = np.array([
[72, 45, 88, 31], # Virat
[56, 0, 74, 88], # Rohit
[45, 32, 0, 67], # Hardik
])
t = scores.T
print("original:", scores.shape, " transposed:", t.shape)
print(t)
print("Rohit, match 3:", scores[1, 2], "==", t[2, 1])
print("same as np.transpose:", np.array_equal(t, np.transpose(scores)))text
original: (3, 4) transposed: (4, 3)
[[72 56 45]
[45 0 32]
[88 74 0]
[31 88 67]]
Rohit, match 3: 74 == 74
same as np.transpose: TrueHow it works: .T turns the 3×4 table into a 4×3 table. Each row of t is now one match, so t[2] reads "everyone's score in match 3". Value 74 moved from [1, 2] to [2, 1].
Why would you transpose data?
| Reason | IPL example |
|---|---|
| 1. Change your analysis perspective | data is players × matches but you want to ask match-centric questions: t[6].argmax() = best player of match 7 |
| 2. Match shapes for an operation | matrix multiplication needs inner dimensions to agree: (3, 4) @ (3, 4) fails but (3, 4) @ (4, 3) works, so you write A @ B.T |
| 3. Fit what another library expects | Pandas and scikit-learn want rows = records/observations, columns = features; if your data is the other way round, transpose it |
| 4. Image data | images are (height, width, channels) but some deep-learning libraries want (channels, height, width) → img.transpose(2, 0, 1) |
Example — match-centric view and a matrix product
python
import numpy as np
players = ["Virat", "Rohit", "Hardik"]
scores = np.array([
[72, 45, 88, 31],
[56, 0, 74, 88],
[45, 32, 0, 67],
])
by_match = scores.T
for m, row in enumerate(by_match, start=1):
print(f"Match {m}: best = {players[row.argmax()]} ({row.max()})")
print("scores @ scores.T shape:", (scores @ scores.T).shape)
try:
scores @ scores
except ValueError as e:
print("scores @ scores fails:", str(e)[:60], "...")text
Match 1: best = Virat (72)
Match 2: best = Virat (45)
Match 3: best = Virat (88)
Match 4: best = Rohit (88)
scores @ scores.T shape: (3, 3)
scores @ scores fails: matmul: Input operand 1 has a mismatch in its core dimension ...How it works: looping over scores.T gives one match per iteration. For @, (3, 4) @ (4, 3) works because the inner sizes (4 and 4) match; (3, 4) @ (3, 4) does not.
Example — 3D arrays: transpose with axes, and swapaxes
python
import numpy as np
# 2 seasons x 3 players x 4 matches
data = np.arange(24).reshape(2, 3, 4)
print("original :", data.shape)
print(".T :", data.T.shape) # reverses all axes
print("transpose(1,0,2):", data.transpose(1, 0, 2).shape) # players first
print("swapaxes(0, 2):", np.swapaxes(data, 0, 2).shape)
print("moveaxis(0, -1):", np.moveaxis(data, 0, -1).shape)
img = np.zeros((4, 6, 3)) # height, width, RGB channels
print("image HWC -> CHW:", img.transpose(2, 0, 1).shape)text
original : (2, 3, 4)
.T : (4, 3, 2)
transpose(1,0,2): (3, 2, 4)
swapaxes(0, 2): (4, 3, 2)
moveaxis(0, -1): (3, 4, 2)
image HWC -> CHW: (3, 4, 6)How it works: axes=(1, 0, 2) means "new axis 0 is old axis 1 (players), new axis 1 is old axis 0 (seasons), axis 2 stays". swapaxes(0, 2) exchanges just those two. moveaxis(0, -1) moves the seasons axis to the end and keeps the others in order.
Example — .T does nothing to a 1D array
python
import numpy as np
v = np.array([72, 45, 88])
print(v.shape, "->", v.T.shape) # unchanged!
print(v.reshape(-1, 1).shape) # a real column
print(v[:, np.newaxis].shape) # also a column
print(v.reshape(1, -1).T.shape) # row (1, 3) -> column (3, 1)text
(3,) -> (3,)
(3, 1)
(3, 1)
(3, 1)How it works: a 1D array has only one axis, so reversing its axes changes nothing. To get a column, first give it a second axis with reshape(-1, 1) or np.newaxis.
Common mistakes
- ❌
scores.T()→TypeError: 'numpy.ndarray' object is not callable. ✅.Tis an attribute:scores.T(or callscores.transpose()). - ❌ Using
.Tto turn a 1D array into a column. ✅v.reshape(-1, 1)orv[:, np.newaxis]. - ❌ Using
reshape(4, 3)when you meant transpose. ✅reshapere-reads in order; only.Tmaps[i, j]to[j, i]. - ❌ Modifying a transposed array and expecting the original to stay the same. ✅
.Tis a view; use.T.copy()for independence.
Comparison — reshape vs transpose on a (2, 3) array
python
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print("a.reshape(3, 2):")
print(a.reshape(3, 2))
print("a.T:")
print(a.T)text
a.reshape(3, 2):
[[1 2]
[3 4]
[5 6]]
a.T:
[[1 4]
[2 5]
[3 6]]a.reshape(3, 2) | a.T | |
|---|---|---|
| Shape | (3, 2) | (3, 2) |
| Row 0 | [1, 2] — next values in reading order | [1, 4] — the old column 0 |
| Meaning of rows | none — just regrouped | old columns |
Interview tip
Q: Does a.T copy the data? How would you check?
A: No, it returns a view — only the strides (how memory is stepped through) change. Check with np.shares_memory(a, a.T) → True. (If a owns its data, a.T.base is a is also True.)
Key points to remember
- Transpose flips rows and columns: shape (r, c) becomes (c, r) and [i, j] moves to [j, i].
- .T is an attribute (no brackets); a.transpose() and np.transpose(a) do the same.
- The transpose is a view — no data is copied.
- For 3D+ arrays, transpose(axes) reorders axes in any order; .T reverses them all.
- swapaxes(i, j) exchanges two axes; moveaxis(src, dst) moves one axis.
- .T does nothing to a 1D array — use reshape(-1, 1) or [:, np.newaxis] for a column.
- Transpose to change perspective (matches × players), to make shapes fit (A @ B.T), or to match what a library expects.
Try it yourself
Players × matches → matches × players
Best performer of each match
Reordering axes in 3D
Practice: match totals via transpose
Revision Flashcards
Tap a card to flip it and see the answer.
