Python:NumPy .swapaxes()

drywantonmee's avatar
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.

  • 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

Syntax

ndarray.swapaxes(axis1, axis2)

Parameters:

  • axis1: An int representing the first axis to be swapped.
  • axis2: An int representing 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 np
arr = 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:

Code
Output
Loading...

All contributors

Contribute to 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