Transposing & Swapping Axes
Reviewed & published by Brayan K
Transposing an array reorders its dimensions — for a 2D array it flips rows and columns — and NumPy does it as a cheap view that shares the original data instead of copying it.
Part of the free NumPy course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You'll transpose matrices with .T and np.transpose, reorder the axes of 3D arrays, swap a pair of axes with swapaxes, relocate an axis with moveaxis, and learn that all of these return views.
What You'll Learn in This Lesson
- Flip rows and columns of a 2D array with .T
- Reorder any number of axes with np.transpose
- Exchange exactly two axes with np.swapaxes
- Relocate an axis with np.moveaxis
- Understand that transpose returns a view, not a copy
- Reorder the axes of a 3D array on purpose
1 .T: Flip Rows and Columns
For a 2D array, the .T attribute swaps the two axes: element (i, j) becomes (j, i), so a shape (2, 3) array becomes (3, 2). It is the classic matrix transpose. Because it is a view, it costs almost nothing even on large arrays.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]]) # shape (2, 3)
m.T
# [[1 4]
# [2 5]
# [3 6]] # shape (3, 2)import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
print("Original shape:", m.shape) # Original shape: (2, 3)
print(m.T)
# [[1 4]
# [2 5]
# [3 6]]
print("Transposed shape:", m.T.shape) # Transposed shape: (3, 2)
# 1D arrays are unchanged by .T
v = np.array([1, 2, 3])
print(v.T.shape) # (3,)
# ✅ Expected output:
# Original shape: (2, 3)
# [[1 4]
# [2 5]
# [3 6]]
# Transposed shape: (3, 2)
# (3,)2 np.transpose with an axes Order
For arrays with more than two dimensions, .T simply reverses every axis, which is often not what you want. np.transpose(arr, axes) lets you specify the exact new order as a permutation of axis numbers. For a 3D array of shape (2, 3, 4), passing (1, 0, 2) gives shape (3, 2, 4).
a = np.arange(24).reshape(2, 3, 4) # shape (2, 3, 4)
np.transpose(a, (1, 0, 2)).shape # (3, 2, 4)
np.transpose(a).shape # (4, 3, 2) -> full reverse, same as a.Timport numpy as np
a = np.arange(24).reshape(2, 3, 4)
print("Original:", a.shape) # Original: (2, 3, 4)
# Swap the first two axes, keep the last
b = np.transpose(a, (1, 0, 2))
print("Reordered:", b.shape) # Reordered: (3, 2, 4)
# No axes argument reverses ALL axes
print("Full reverse:", np.transpose(a).shape) # Full reverse: (4, 3, 2)
# Confirm an element moved as expected
print(a[0, 1, 2], b[1, 0, 2]) # 6 6
# ✅ Expected output:
# Original: (2, 3, 4)
# Reordered: (3, 2, 4)
# Full reverse: (4, 3, 2)
# 6 63 swapaxes, moveaxis, and the View Catch
When you only want to exchange two axes, np.swapaxes(arr, a, b) is the clearest tool. When you want to relocate an axis to a new position while the others shift to fill the gap, use np.moveaxis(arr, source, destination). All of these — like .T and np.transpose — return a view, so edits flow back to the original.
a = np.arange(24).reshape(2, 3, 4)
np.swapaxes(a, 0, 2).shape # (4, 3, 2) -> swap axes 0 and 2
np.moveaxis(a, 0, -1).shape # (3, 4, 2) -> move axis 0 to the endimport numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(np.swapaxes(a, 0, 2).shape) # (4, 3, 2)
print(np.moveaxis(a, 0, -1).shape) # (3, 4, 2)
# Transpose returns a VIEW, so writing flows back
m = np.array([[1, 2],
[3, 4]])
t = m.T
t[0, 1] = 99 # this is m[1, 0]
print(m)
# [[ 1 2]
# [99 4]]
# ✅ Expected output:
# (4, 3, 2)
# (3, 4, 2)
# [[ 1 2]
# [99 4]]🎯 YOUR TURN: Fill in the Blank
Transpose the matrix so its shape becomes (3, 2) by filling in the attribute.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]]) # shape (2, 3)
# Flip rows and columns with the transpose attribute
flipped = m.___
print(flipped.shape) # (3, 2)
print(flipped)
# Expected output:
# [[1 4]
# [2 5]
# [3 6]]Answer: T (so m.T). Equivalent calls are np.transpose(m) and np.swapaxes(m, 0, 1).
! Common Errors (And How to Fix Them)
❌ Expecting .T to make a 1D vector a column
A 1D array has one axis, so .T is a no-op:
np.array([1, 2, 3]).T.shape # (3,) -- still a 1D array✅ Fix: add an axis to make a real column:
np.array([1, 2, 3]).reshape(-1, 1) # shape (3, 1)❌ Editing a transpose and surprising the original
Transpose returns a view, so writes propagate back to the source array.
✅ Fix: use arr.T.copy() when you need an independent array to modify.
❌ Using .T on a 3D array and getting the wrong order
On 3D+ arrays .T reverses every axis, which is rarely the intended reorder.
✅ Fix: pass an explicit order to np.transpose(arr, (...)) or use np.swapaxes / np.moveaxis.
🎯 Mini Challenge: Reorder an Image Tensor
Image data often comes as (height, width, channels) but some libraries want (channels, height, width). Convert between the two with moveaxis.
import numpy as np
# Fake image: height 4, width 5, 3 color channels
img = np.arange(4 * 5 * 3).reshape(4, 5, 3)
print("HWC:", img.shape) # HWC: (4, 5, 3)
# Move the channel axis (last) to the front -> CHW
chw = np.moveaxis(img, -1, 0)
print("CHW:", chw.shape) # CHW: (3, 4, 5)
# Move it back to confirm we can round-trip
back = np.moveaxis(chw, 0, -1)
print("Back to HWC:", back.shape) # Back to HWC: (4, 5, 3)
print("Round-trip equal:", np.array_equal(img, back)) # Round-trip equal: True
# ✅ Expected output:
# HWC: (4, 5, 3)
# CHW: (3, 4, 5)
# Back to HWC: (4, 5, 3)
# Round-trip equal: True❓ Frequently Asked Questions
Lesson complete — you can reorder any axis!
You can transpose with .T, reorder axes precisely with np.transpose, swap a pair with np.swapaxes, relocate one with np.moveaxis, and you know all of these return views.
Practice quiz
For a 2D array of shape (2, 3), what shape does .T give?
- (2, 3)
- (6,)
- (3, 2)
- (2, 2)
Answer: (3, 2). .T swaps the two axes, turning (2, 3) into (3, 2).
Does transposing an array copy the data?
- No, it returns a view sharing the same data
- Yes, always a full copy
- Only for 1D arrays
- Only when the array is large
Answer: No, it returns a view sharing the same data. .T and np.transpose return a view; only shape and strides change.
What does .T do to a 1D array like [1, 2, 3]?
- Raises an error
- Leaves it unchanged (still 1D)
- Makes it a column
- Reverses the values
Answer: Leaves it unchanged (still 1D). A 1D array has one axis, so .T is a no-op; shape stays (3,).
For a (2, 3, 4) array, what shape does np.transpose(a, (1, 0, 2)) give?
- (2, 3, 4)
- (4, 3, 2)
- (2, 4, 3)
- (3, 2, 4)
Answer: (3, 2, 4). The permutation puts old axis 1 first, old axis 0 second, axis 2 last.
What does np.transpose(a) with no axes argument do?
- Returns a copy
- Keeps the shape
- Reverses the order of all axes
- Swaps only the first two axes
Answer: Reverses the order of all axes. With no axes it reverses every dimension, the same as a.T.
Which function exchanges exactly two axes?
- np.moveaxis
- np.swapaxes
- np.reshape
- np.ravel
Answer: np.swapaxes. np.swapaxes(arr, a, b) exchanges exactly two axes.
Which function relocates an axis to a new position?
- np.moveaxis
- np.swapaxes
- np.flatten
- np.tile
Answer: np.moveaxis. np.moveaxis slides axes from source to destination positions.
After t = m.T, what happens if you write t[0, 1] = 99?
- Nothing changes
- It raises an error
- Only t changes
- m changes too, because t is a view
Answer: m changes too, because t is a view. Transpose returns a view, so writes flow back to the original m.
For a (2, 3, 4) array, what shape does np.swapaxes(a, 0, 2) give?
- (3, 2, 4)
- (4, 3, 2)
- (2, 4, 3)
- (2, 3, 4)
Answer: (4, 3, 2). Swapping axes 0 and 2 turns (2, 3, 4) into (4, 3, 2).
To convert an image from (H, W, C) to (C, H, W), which is cleanest?
- a.T
- np.reshape(a, (3, 4, 5))
- np.moveaxis(img, -1, 0)
- np.swapaxes(img, 0, 1)
Answer: np.moveaxis(img, -1, 0). moveaxis(img, -1, 0) moves the channel axis to the front.
Continue this course
- Previous: Adding Axes: newaxis & expand_dims
- Next: Dates & Times with datetime64 — Do date arithmetic with datetime64 and timedelta64 and their units
- Quick reference: NumPy cheat sheet
Frequently asked questions
Does transposing an array copy the data?
No. Both .T and np.transpose return a view that shares the same underlying data as the original array; only the shape and the internal strides change. That makes transposing essentially free, but it also means writing into the transposed array writes back into the original. Call .copy() if you need an independent array.
What does the axes argument of np.transpose mean?
np.transpose(arr, axes) reorders the dimensions according to the permutation you give. For a 3D array of shape (2, 3, 4), transpose(arr, (1, 0, 2)) produces shape (3, 2, 4) because the new axis 0 is the old axis 1, the new axis 1 is the old axis 0, and axis 2 stays put. With no axes argument it reverses the order of all dimensions.
What is the difference between swapaxes and moveaxis?
np.swapaxes(arr, a, b) exchanges exactly two axes and leaves the rest alone. np.moveaxis(arr, source, destination) takes one or more axes from their source positions and slides them to new destination positions, shifting the others to fill the gap. moveaxis is more flexible when you want to relocate an axis rather than just swap a pair.
Why does .T do nothing useful on a 1D array?
A 1D array has only one axis, so reversing the axis order leaves it unchanged: arr.T is the same shape as arr. To turn a 1D vector into a column you must add an axis first, for example arr[:, np.newaxis] or arr.reshape(-1, 1), because there is no second dimension to transpose into.