NumPy ndarray.swapaxes()

The numpy.ndarray.swapaxes() method swaps two specified axes of a NumPy array. This is useful when working with multidimensional data and needing to rearrange dimensions.

Syntax

</>
Copy
ndarray.swapaxes(axis1, axis2)

Parameters

ParameterTypeDescription
axis1intThe first axis to be swapped.
axis2intThe second axis to be swapped.

Return Value

Returns a new array with the specified axes swapped. The original array remains unchanged.


Examples

1. Swapping Two Axes in a 2D Array

In this example, we swap the row and column axes (0 and 1) in a 2D array.

</>
Copy
import numpy as np

# Creating a 2D NumPy array
arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# Swapping axes 0 and 1 (rows and columns)
swapped = arr.swapaxes(0, 1)

# Printing the original and swapped arrays
print("Original array:")
print(arr)

print("\nArray after swapping axes 0 and 1:")
print(swapped)

Output:

Original array:
[[1 2 3]
 [4 5 6]]

Array after swapping axes 0 and 1:
[[1 4]
 [2 5]
 [3 6]]

Since we swapped axis 0 (rows) with axis 1 (columns), the shape changed from (2,3) to (3,2), effectively transposing the array.

2. Swapping Axes in a 3D Array

Here, we swap axes in a 3D array to rearrange dimensions.

</>
Copy
import numpy as np

# Creating a 3D NumPy array
arr = np.array([[[1, 2], [3, 4]],
                [[5, 6], [7, 8]]])

# Swapping axes 0 and 2
swapped = arr.swapaxes(0, 2)

# Printing the original and swapped arrays
print("Original array shape:", arr.shape)
print("Original array:\n", arr)

print("\nSwapped array shape:", swapped.shape)
print("Array after swapping axes 0 and 2:\n", swapped)

Output:

Original array shape: (2, 2, 2)
Original array:
 [[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

Swapped array shape: (2, 2, 2)
Array after swapping axes 0 and 2:
 [[[1 5]
  [3 7]]

 [[2 6]
  [4 8]]]

Swapping axes 0 and 2 changes how data is accessed, rearranging the elements while keeping the shape consistent.

3. Swapping Axes in a 4D Array

This example demonstrates swapping axes in a higher-dimensional array.

</>
Copy
import numpy as np

# Creating a 4D NumPy array
arr = np.random.randint(1, 10, (2, 3, 4, 5))  # Shape (2,3,4,5)

# Swapping axes 1 and 3
swapped = arr.swapaxes(1, 3)

# Printing the original and swapped shapes
print("Original shape:", arr.shape)
print("Swapped shape:", swapped.shape)

Output:

Original shape: (2, 3, 4, 5)
Swapped shape: (2, 5, 4, 3)

Here, swapping axes 1 and 3 changed the array shape from (2,3,4,5) to (2,5,4,3), modifying how data is structured while keeping the total number of elements constant.