Numpy transpose function reverses or permutes the axes of an array, and it returns the modified array. For an array, with two axes, transpose(a) gives the matrix transpose. The transpose of the 1D array is still a 1D array. Before we proceed further, let’s learn the difference between Numpy matrices and Numpy arrays.
A ndarray is an (it is usually fixed-size) multidimensional container of elements of the same type and size. The number of dimensions and items in the array is defined by its shape, which is the tuple of N non-negative integers that specify the sizes of each dimension.
The type of elements in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray. As with other container objects in Python, the contents of a ndarray can be accessed and modified by indexing or slicing the array (using, for example, N integers), and via the methods and attributes of the ndarray.
numpy.transpose(arr, axis=None)
arr: array_like
axis: List of ints()
This function returns a ndarray. The output array is the source array, with its axis permuted. A view is returned whenever possible.
import numpy as np
data = np.arange(6).reshape((2, 3))
print("Original Array")
print(data)
tMat = np.transpose(data)
print("Transposed Array")
print(tMat)
Output
Original Array
[[0 1 2]
[3 4 5]]
Transposed Array
[[0 3]
[1 4]
[2 5]]
In Python, you can get a transposed matrix of the original two-dimensional array (matrix) with the T attribute.
import numpy as np
arr2d = np.arange(6).reshape(2, 3)
print(arr2d)
print('\n')
print('After using T attribute: ')
arr2d_T = arr2d.T
print(arr2d_T)
Output
[[0 1 2]
[3 4 5]]
After using T attribute:
[[0 3]
[1 4]
[2 5]]
The transpose() is provided as a method of ndarray. Like T, the view is returned.
import numpy as np
arr2d = np.arange(6).reshape(2, 3)
print(arr2d)
print('\n')
print('After using transpose() function: ')
arr2d_T = arr2d.transpose()
print(arr2d_T)
Output
[[0 1 2]
[3 4 5]]
After using transpose() function:
[[0 3]
[1 4]
[2 5]]
That’s it.
Thanks for reading !!!
#numpy #python