numpy.moveaxis() function | Python

Last Updated : 9 Apr, 2025

numpy.moveaxis() function allows you to rearrange axes of an array. It is used when you need to shift dimensions of an array to different positions without altering the actual data.

The syntax for the numpy.moveaxis() function is as follows:

numpy.moveaxis(array, source, destination)

Parameters:

  • array: input array whose axes are to be moved.
  • source: The original position(s) of the axis (or axes) that you want to move. This can be a single integer or a list/tuple of integers.
  • destination: The new position(s) where the specified axes should be placed. Like source, this can also be a single integer or a list/tuple of integers.

How numpy.moveaxis() Works?

1. Moving a Single Axis

If you want to move a single axis of an array, specify the axis to move (source) and where to move it (destination).

Python
import numpy as np

arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("Original Array:")
print(arr)
print("Shape of Original Array: ", arr.shape)

# Move axis 0 to position 2
moved_arr = np.moveaxis(arr, 0, 2)

print("\nArray after moveaxis:")
print(moved_arr)
print("Shape of Array after moveaxis: ", moved_arr)

Output :