numpy.moveaxis() function | Python
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. Likesource
, 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).
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 :
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.
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()
?
- Compared to
transpose()
orswapaxes()
,moveaxis()
is simple to use and rearrange the axes without complex permutations. - moveaxis() allows easy rearrangement of one or multiple axes without modifying the data.
- 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.