Python:NumPy .swapaxes()
Published Aug 6, 2025
Contribute to Docs
NumPy’s .swapaxes() method returns a view of the array with the specified axes interchanged, without copying data. It’s useful for reorienting multi-dimensional arrays for analysis, transformation, or visualization.
Syntax
ndarray.swapaxes(axis1, axis2)
Parameters:
axis1: Anintrepresenting the first axis to be swapped.axis2: Anintrepresenting the second axis to be swapped.
Return value:
Returns an ndarray view of the original array with axis1 and axis2 interchanged. The shape of the returned array is the same as the original, but with the specified axes swapped.
Example
This example creates a 2D array and then swaps its axes using .swapaxes():
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])swapped_arr = arr.swapaxes(0, 1)print(swapped_arr)
Here is the output:
[[1 4][2 5][3 6]]
Codebyte Example
This codebyte example demonstrates the use of .swapaxes() on a 3D array:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours