Monday, June 1, 2020

Numpy array transpose

Array Transpose


numpy.transpose()


The numpy.transpose() method returns transpose of a matrix. The transpose of a matrix is obtained by moving row data into column and column data into rows. If the shape of the matrix is (m,n), its transpose matrix shape will be (n,m). It works with array-like objects.



The syntax of the function is,

numpy.transpose(arr, axes)
for example,

import numpy as np

nums = np.array([[10,12],[14,16],[18,20],[22,24]])
print('======nums========\n',nums)
print('======transpose===\n',np.transpose(nums))

#Output
======nums========
 [[10 12]
 [14 16]
 [18 20]
 [22 24]]
======transpose===
 [[10 14 18 22]
 [12 16 20 24]]

numpy.ndarray.T


numpy.ndarray.T works like numpy.transpose() method. This belongs to Numpy ndarray class.

import numpy as np

nums = np.array([[10,12],[14,16],[18,20],[22,24]])
print('======nums========\n',nums)
print('======transpose===\n',nums.T)

#Output
======nums========
 [[10 12]
 [14 16]
 [18 20]
 [22 24]]
======transpose===
 [[10 14 18 22]
 [12 16 20 24]]

numpy.rollaxis()


The numpy.rollaxis() method rolls the provided axis backward until it lies in a given position. The  syntax of this method is,

numpy.rollaxis(arr, axis, start)
For example,

import numpy as np

nums = np.array([[10,12],[14,16],[18,20],[22,24]])
print('======nums========\n',nums)
print('======Roll axis===\n',np.rollaxis(nums,1))

#Output
======nums========
 [[10 12]
 [14 16]
 [18 20]
 [22 24]]
======Roll axis===
 [[10 14 18 22]
 [12 16 20 24]]

numpy.swapaxes()


This method can swap the axes of the array and return a view of swapped axes.
The syntax of this method is,

numpy.swapaxes(arr, axis1, axis2)

For example,

import numpy as np

nums = np.array([[10,12],[14,16],[18,20],[22,24]])
arr = np.arange(27).reshape(3,3,3)
print('======nums========\n',nums)
print('======Swap axis===\n',np.swapaxes(nums,0,1))

print('======arr========\n',arr)
print('======Swap axis===\n',np.swapaxes(arr,2,0))
#Output
======nums========
 [[10 12]
 [14 16]
 [18 20]
 [22 24]]
======Swap axis===
 [[10 14 18 22]
 [12 16 20 24]]
======arr========
 [[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]
======Swap axis===
 [[[ 0  9 18]
  [ 3 12 21]
  [ 6 15 24]]

 [[ 1 10 19]
  [ 4 13 22]
  [ 7 16 25]]

 [[ 2 11 20]
  [ 5 14 23]
  [ 8 17 26]]]