Numpy transpose() Method Example

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.

Syntax

numpy.transpose(arr, axis=None)  

Parameters

arr: array_like

  • It is an ndarray. It is the source array whose elements we want to transpose. This parameter is essential and plays a vital role in numpy.transpose() function.

axis: List of ints()

  • If we didn't specify the axis, then by default, it reverses the dimensions otherwise permute the axis according to the given values.

Return

This function returns a ndarray. The output array is the source array, with its axis permuted. A view is returned whenever possible.

Example 1: How to Use np.transpose() Method

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]]

Example 2: Using the T attribute

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]]

Example 3: Provide an ndarray

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

Numpy transpose() Method Example
3.95 GEEK