w3resource

How to swap axes of a 3D NumPy array?


13. 3D Array Swapaxes Operation

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.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to swap two axes of a 3D array using swapaxes() and verify the change in shape and strides.
  • Write a NumPy program to swap multiple pairs of axes on a 3D array and then reverse the swaps to retrieve the original array.
  • Write a NumPy program to perform the same axis swap using both swapaxes() and transpose() and compare the outputs.
  • Write a NumPy program to analyze how swapaxes() affects the memory layout by printing the strides before and after the swap.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: How to flatten and reshape a 2D NumPy array?
Next: How to flatten a 2D NumPy array in 'C' and 'F' order?.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.