Unlike np.transpose(), which reorders all axes at once, whether by full reversal or an explicit full permutation, swapaxes() targets exactly two axes by their integer position and exchanges them, leaving the rest of the array's structure untouched, which is often simpler to reason about when you only need to fix one specific pair of dimensions, rather than specifying a complete new ordering for every axis.
1Understanding np.swapaxes()
Unlike np.transpose(), which reorders all axes at once, whether by full reversal or an explicit full permutation, swapaxes() targets exactly two axes by their integer position and exchanges them, leaving the rest of the array's structure untouched, which is often simpler to reason about when you only need to fix one specific pair of dimensions, rather than specifying a complete new ordering for every axis.
Use swapaxes() when you only need to exchange two specific axes and want to leave everything else alone — it avoids having to think through and write out a full axis-order tuple the way np.transpose() with explicit axes would require.
import numpy as np
arr = np.arange(24).reshape(2, 3, 4)
swapped = np.swapaxes(arr, 0, 2)
print(swapped.shape)2Practical Example
Here is a real-world application of np.swapaxes() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(np.swapaxes(matrix, 0, 1))3Best Practices
Follow these guidelines when working with np.swapaxes():
1. Use swapaxes() for a targeted two-axis swap instead of writing out a full axes tuple for np.transpose() when only two dimensions actually need to change
2. Verify the resulting .shape after any axis swap on higher-dimensional data, since axis positions are easy to miscount
3. Remember swapaxes() returns a view, not a copy, the same as transpose() and .T
Tip: Use swapaxes() when you only need to exchange two specific axes and want to leave everything else alone — it avoids having to think through and write out a full axis-order tuple the way np.transpose() with explicit axes would require.
import numpy as np
arr = np.arange(24).reshape(2, 3, 4)
swapped = np.swapaxes(arr, 0, 2)
print(swapped.shape)