Skip to content

Commit 5913b8d

Browse files
authored
[Term Entry] NumPy Ndarray: .swapaxes()
* Add documentation for numpy.ndarray.swapaxes * minor fixes * Minor changes ---------
1 parent ad795fc commit 5913b8d

File tree

1 file changed

+64
-0
lines changed
  • content/numpy/concepts/ndarray/terms/swapaxes

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
Title: '.swapaxes()'
3+
Description: 'Returns a view of the array with two axes interchanged.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Data Structures'
10+
- 'Functions'
11+
- 'NumPy'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/data-science'
15+
---
16+
17+
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.
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.swapaxes(axis1, axis2)
23+
```
24+
25+
**Parameters:**
26+
27+
- `axis1`: An `int` representing the first axis to be swapped.
28+
- `axis2`: An `int` representing the second axis to be swapped.
29+
30+
**Return value:**
31+
32+
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.
33+
34+
## Example
35+
36+
This example creates a 2D array and then swaps its axes using `.swapaxes()`:
37+
38+
```py
39+
import numpy as np
40+
41+
arr = np.array([[1, 2, 3], [4, 5, 6]])
42+
swapped_arr = arr.swapaxes(0, 1)
43+
print(swapped_arr)
44+
```
45+
46+
Here is the output:
47+
48+
```shell
49+
[[1 4]
50+
[2 5]
51+
[3 6]]
52+
```
53+
54+
## Codebyte Example
55+
56+
This codebyte example demonstrates the use of `.swapaxes()` on a 3D array:
57+
58+
```codebyte/python
59+
import numpy as np
60+
61+
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
62+
swapped_arr = arr.swapaxes(0, 2)
63+
print(swapped_arr)
64+
```

0 commit comments

Comments
 (0)