Skip to content

[Term Entry] NumPy Ndarray: .swapaxes() #7306 #7371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions content/numpy/concepts/ndarray/terms/swapaxes/swapaxes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
Title: '.swapaxes()'
Description: 'Returns a view of the array with two axes interchanged.'
Subjects:
- 'Computer Science'
- 'Data Science'
Tags:
- 'Arrays'
- 'Data Structures'
- 'Functions'
- 'NumPy'
CatalogContent:
- 'learn-python-3'
- 'paths/data-science'
---

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

```pseudo
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

The following example creates a 2D array and then swaps its axes:

```py
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
swapped_arr = arr.swapaxes(0, 1)
print(swapped_arr)
```

The code above generates the following output:

```shell
[[1 4]
[2 5]
[3 6]]
```

## Codebyte Example

The following codebyte example demonstrates the use of `.swapaxes()` on a 3D array.

```codebyte/python
import numpy as np

arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
swapped_arr = arr.swapaxes(0, 2)
print(swapped_arr)
```