w3resource

How to swap axes of a 3D NumPy array?

NumPy: Memory Layout Exercise-13 with Solution

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/swap-axes-of-a-3d-numpy-array.php