numpy.moveaxis() function | Python (original) (raw)

Last Updated : 09 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:

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 :

Capture

We have moved axis 0 (first axis) to position 2 (last position). result is an array where the original first dimension becomes the third dimension.

2. Moving Multiple Axes

You can also move multiple axes at once by passing sequences to both the source and destination parameters.

Python `

import numpy as np arr = np.random.rand(2, 3, 4)

result = np.moveaxis(arr, source=[0, 1], destination=[1, 0])

print("Original shape:", arr.shape) print("New shape:", result.shape)

`

**Output :

Original shape: (2, 3, 4)
New shape: (3, 2, 4)

Why Use numpy.moveaxis()?

  1. Compared to transpose() or swapaxes(), moveaxis() is simple to use and rearrange the axes without complex permutations.
  2. moveaxis() allows easy rearrangement of one or multiple axes without modifying the data.
  3. The function does not create a new copy of the array but rather rearranges the axes. This makes it efficient when working with large datasets.

By understanding the use of moveaxis(), you can streamline data manipulation tasks.

Similar Reads

Introduction







Creating NumPy Array













NumPy Array Manipulation


















Matrix in NumPy


















Operations on NumPy Array




Reshaping NumPy Array















Indexing NumPy Array






Arithmetic operations on NumPyArray










Linear Algebra in NumPy Array