w3resource

How to swap axes of a 3D NumPy array?


Write a NumPy program that creates a 3D array of shape (2, 3, 3) and use swapaxes() to swap the first and third axes. Print the original and modified arrays.

Sample Solution:

Python Code:

import numpy as np

# Create a 3D array of shape (2, 3, 3)
array_3d = np.array([[[1, 2, 3],
                      [4, 5, 6],
                      [7, 8, 9]],
                     
                     [[10, 11, 12],
                      [13, 14, 15],
                      [16, 17, 18]]])

# Print the original array
print("Original array:\n", array_3d)

# Use swapaxes() to swap the first and third axes
swapped_array = np.swapaxes(array_3d, 0, 2)

# Print the modified array
print("Array after swapping first and third axes:\n", swapped_array)

Output:

Original array:
 [[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[10 11 12]
  [13 14 15]
  [16 17 18]]]
Array after swapping first and third axes:
 [[[ 1 10]
  [ 4 13]
  [ 7 16]]

 [[ 2 11]
  [ 5 14]
  [ 8 17]]

 [[ 3 12]
  [ 6 15]
  [ 9 18]]]

Explanation:

  • Import NumPy library: We start by importing the NumPy library to handle array operations.
  • Create a 3D array: We create a 3D array array_3d of shape (2, 3, 3) using np.array().
  • Print the original array: We print the array_3d to display the original array.
  • Swap axes: We use swapaxes() to swap the first and third axes of array_3d, resulting in swapped_array.
  • Print the modified array: We print swapped_array to display the array after swapping the first and third axes.

Python-Numpy Code Editor: