Prepare multidimensional data
Reordering dimensions before an operation that expects a particular axis layout.
NumPy · Function
Interchanges two axes of an array. It is useful for changing dimension order while leaving the data values unchanged.
swapaxes returns an array whose two selected dimensions exchange positions while all other axes remain in their original order. For an ndarray, the result is a view; for other inputs, NumPy creates a new array.
numpy.swapaxes(a, axis1, axis2)| Name | Type | Description |
|---|---|---|
a | array_like | Input array or array-like object whose axes will be exchanged. |
axis1 | int | First axis to interchange. |
axis2 | int | Second axis to interchange. |
a_swapped ndarray. For NumPy >= 1.10.0, an ndarray input produces a view; otherwise a new array is created.
axis1 is the integer index of the first dimension to exchange.axis2 is the integer index of the second dimension to exchange.import numpy as np
x = np.array([[[0, 1], [2, 3]],
[[4, 5], [6, 7]]])
y = np.swapaxes(x, 0, 2)
print(y.shape) # (2, 2, 2)
print(y[:, :, 0])
This exchanges axes 0 and 2, changing how the same elements are indexed.
Reordering dimensions before an operation that expects a particular axis layout.
Changing channel, batch, or spatial dimension placement in tensor-like arrays.
Avoiding an unnecessary data copy when working with ndarray inputs.
numpy.swapaxes do?It exchanges the positions of two axes and returns the resulting array. The two axes are selected with axis1 and axis2; dimensions not selected retain their relative order.
Follow-up: How does it differ from transpose? transpose can specify a complete axis permutation, while swapaxes performs the focused operation of exchanging two axes.
axis1 identifies the first axis and axis2 identifies the second axis. The function returns an ndarray with those axes interchanged.
Follow-up: What happens if the same axis is supplied twice? The axis order is unchanged, so the result has the same shape and indexing arrangement as the input.
swapaxes copy its input?For an ndarray input, NumPy returns a view rather than copying the data. If the input is not an ndarray, NumPy creates a new array.
Follow-up: Why can this matter? Mutating a writable result may mutate the original ndarray because both can refer to the same underlying data.
numpy.transposenumpy.moveaxisnumpy.rollaxisnumpy.ndarray.swapaxes