Numpy transpose() Function
The Numpy transpose() Function permutes the dimension of the given array. It returns a view wherever possible. It's commonly used in data manipulation, scientific computing, and machine learning tasks where multidimensional arrays are prevalent.
By default this function reverse the dimensions of the array. The array is transposed according to the value of axes.
If we want to transpose the array according to a specific order then we can pass the desired order of the axes. For example, if we have a 3D array and we want to swap the first and the last axis, we can pass (2, 1, 0).
Syntax
The syntax for the Numpy transpose() function is as follows −
numpy.transpose(a, axes=None)
Parameters
Below are the parameters of the Numpy transpose() Function −
- a : The array to be transposed.
- axes : tuple or list of ints, optional
Return Value
The transpose() function returns the transposed array with the same data type as the input array.
Example 1
Following is the example of the numpy transpose() function in which transpose operation switches the rows and columns of the 2D array −
import numpy as np
# Original 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Transposing the 2D array
transposed_2d = np.transpose(array_2d)
print("Original array:\n", array_2d)
print("Transposed array:\n", transposed_2d)
Output
Original array: [[1 2 3] [4 5 6]] Transposed array: [[1 4] [2 5] [3 6]]
Example 2
Here in this example we will use the swapaxes() function to swap specified axes in a 3-dimensional ndarray, effectively reordering the dimensions of the array −
import numpy as np
# Original 3D array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Transposing the 3D array with specified axes
transposed_3d = np.transpose(array_3d, axes=(1, 0, 2))
print("Original array:\n", array_3d)
print("Transposed array with axes (1, 0, 2):\n", transposed_3d)
Output
Original array: [[[1 2] [3 4]] [[5 6] [7 8]]] Transposed array with axes (1, 0, 2): [[[1 2] [5 6]] [[3 4] [7 8]]]