Reposition a feature axis
A tensor stores channels or features in an inconvenient dimension and downstream code expects them elsewhere.
NumPy · Function
Moves selected axes of an array to new positions while preserving the relative order of axes that are not moved. The result is a view of the input array.
np.moveaxis returns an array whose selected axes are relocated to specified destination positions. The axes not selected retain their relative order, and the result is a view of the input rather than an independently copied array.
numpy.moveaxis(a, source, destination)| Name | Type | Description |
|---|---|---|
a | np.ndarray | The array whose axes should be reordered. |
source | int or sequence of int | Original positions of the axes to move. Entries must be unique. |
destination | int or sequence of int | Destination positions for each original axis. Entries must be unique. |
result — np.ndarray: An array with moved axes; this is a view of the input array.
import numpy as np
x = np.zeros((3, 4, 5))
y = np.moveaxis(x, 0, -1)
print(y.shape) # (4, 5, 3)Moves the first axis to the end while retaining the relative order of the other axes.
A tensor stores channels or features in an inconvenient dimension and downstream code expects them elsewhere.
Several dimensions need coordinated placement while untouched dimensions should keep their ordering.
An array must be reordered without deliberately allocating a separate data copy.
It reorders selected axes to requested positions while preserving the order of all other axes. The returned array is a view of the input.
Follow-up: How can several axes be moved together? Pass sequences for source and destination, pairing each source axis with its corresponding destination.
For an array with shape (3, 4, 5), moving axis 0 to -1 produces shape (4, 5, 3). Negative positions are accepted as demonstrated by the documented examples.
Follow-up: What must be checked when using multiple axes? Source and destination entries must each be unique.
Use np.moveaxis when specific axes should be relocated and the remaining axes should retain their order. np.swapaxes is the related operation for interchanging two axes, while np.transpose provides broader axis permutation.
Follow-up: When is swapaxes more direct? When exactly two axes need to be interchanged rather than positioned independently.
swapaxestransposerollaxis