How To Transpose A Matrix In Python?

A matrix is a rectangular array of numbers arranged in the form of rows and columns. Transpose is an operation performed on matrices that exchanges the rows with columns and vice versa. For the matrix (M, N) where M corresponds to a number of rows and N corresponds to the number of columns, transposing it will give us a matrix of dimensions (N, M). This article is about how to transpose a matrix in Python.  If you want to learn more about Python Programming, Visit Python Programming Tutorials.

There are several ways to transpose a matrix in Python but we will discuss the six most efficient methods in this tutorial.

Method 01: Using np.array() function for matrix transposition 

An array is a rectangular arrangement of data in a computer program. Arrays are arranged by rows, columns, or pages, and the values stored in an array can be both selected and calculated. A Python matrix is one special type of array that stores numerical/mathematical data. This type of matrix is also included in NumPy package which provides fast, flexible, powerful, and easy-to-use N-dimensional arrays. The matrix is a great way to store data in a rectangular fashion and manipulate it based on its locality.

Getting started with matrixes need a numpy library. So import numpy library first.

import numpy as np

A Python matrix is a rectangular two-dimensional array of data stored in rows and columns. Each entry in a matrix is identified by its row and column. Matrices are similar to lists but they are more general. The data in a matrix can be numbers, strings, expressions, symbols, etc. 

import numpy as np
my_matrix=[[2,'*','*','*'],['*',0,'*','*'],['*','*',2,'*'], ['*','*','*',3]]
my_matrix
[[2, '*', '*', '*'],
 ['*', 0, '*', '*'],
 ['*', '*', 2, '*'],
 ['*', '*', '*', 3]]

To transpose this matrix, we need to convert it into array for which we use np.array() command.

my_matrix=np.array(my_matrix)
my_matrix
array([['2', '*', '*', '*'],
       ['*', '0', '*', '*'],
       ['*', '*', '2', '*'],
       ['*', '*', '*', '3']], dtype='<U11')

The transpose function can be applied by using NumPy array attribute T as shown i the code snippet below.

my_matrix.T
array([['2', '*', '*', '*'],
       ['*', '0', '*', '*'],
       ['*', '*', '2', '*'],
       ['*', '*', '*', '3']], dtype='<U11')

Method 02: Using the zip() function within the unpack function to perform matrix transposition

When asterisk * operator is used within the zip () function, it passes arguments containing the contents of the lists to the zip function. Using zip (*my_matrix), you can create an iterator that aggregates items from each iterator. The single asterisk (*) means it unpacks the iterators. The inverse of zip(*my_matrix) is matrix transposition, so zip(*my_matrix) is matrix transposition.

import numpy as np
my_matrix=[[2,'*','*','*'],['*',0,'*','*'],['*','*',2,'*'], ['*','*','*',3]]
my_matrix=[*zip(*my_matrix)]
my_matrix
[(2, '*', '*', '*'),
 ('*', 0, '*', '*'),
 ('*', '*', 2, '*'),
 ('*', '*', '*', 3)]

Then convert this list into array format using np.array and convert this array to matrix format using np.asmatrix() command. 

my_matrix=np.array(my_matrix)
print('the Transpose of matrix', '\n',my_matrix)
the Transpose of matrix 
 [['2' '*' '*' '*']
 ['*' '0' '*' '*']
 ['*' '*' '2' '*']
 ['*' '*' '*' '3']]

Method 03: Using zip(*iterator) with for..in structure to get matrix transposition  

For..in structure, the method helps to perform the transpose of a matrix in Python. Zip(*iterator) performs matrix transposition task. 

import numpy as np
my_matrix=[[2,'*','*','*'],['*',0,'*','*'],['*','*',2,'*'], ['*','*','*',3]]
my_matrix=[list(i) for i in zip(*my_matrix)]
my_matrix
[[2, '*', '*', '*'],
 ['*', 0, '*', '*'],
 ['*', '*', 2, '*'],
 ['*', '*', '*', 3]]

Rearranging the list in matrix format. 

my_matrix=np.array(my_matrix)
print('the Transpose of matrix', '\n',my_matrix)
the Transpose of matrix 
 [['2' '*' '*' '*']
 ['*' '0' '*' '*']
 ['*' '*' '2' '*']
 ['*' '*' '*' '3']]

Method 04: to transpose of a matrix using itertools.zip_longest (*iterator) method

When using itertools, you can iterate much faster than you would with a standard Python for loop. For-loops are used to step over data structures with itertools, a Python module. 

No value can be defined with the None keyword here.

Theitertools.zip_longest(*my_matrix)function prints the values of iterates in a specific order. One iterable is printed fully if the fill value parameter is set to the value. Here filled by None. 

import itertools
my_matrix=[[1,2,3],[4,6],[7,8]]
my_matrix=list(itertools.zip_longest(*my_matrix))
my_matrix
[(1, 4, 7), (2, 6, 8), (3, None, None)]
my_matrix=np.array(my_matrix)
print('the Transpose of matrix', '\n',my_matrix)
the Transpose of matrix 
 [[1 4 7]
 [2 6 8]
 [3 None None]]

Method 05: Nested List Comprehension to acquire matrix transpose

Using the Nested List comprehension method, it’s possible to perform the transposition task in Matrix in Python, in a more Pythonic way. 

The execution executes in this manner:

  • len(my_matrix) returns the row size of the matrix. Which is 3.
  • We will now iterate over a range(n) using a for a loop. The outer list comprehension for..in structure makes 3(n=3) rows, however, the inner list comprehension for..in structure puts respective values/elements into these 3 rows, after computing transpose. 
  • Now for..in structure to perform the transposition task in Python.
my_matrix=[[1,2,3],[4,5,6],[7,8,9]]
n = len(my_matrix)
transpose = [[row[i] for row in my_matrix] for i in range(n)]
transpose
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
my_matrix=np.array(transpose)
print('the Transpose of matrix', '\n',my_matrix)
the Transpose of matrix 
 [[1 4 7]
 [2 5 8]
 [3 6 9]]

Doing the above code in a single line in a more Pythonic way using list Comprehension to get the transpose of a matrix. 

import numpy as np
my_matrix=[[2,'*','*','*'],['*',0,'*','*'],['*','*',2,'*'], ['*','*','*',3]]
transpose = [[my_matrix[y][x] for y in range(len(my_matrix))] for x in range(len(my_matrix[0]))]
transpose
[[2, '*', '*', '*'],
 ['*', 0, '*', '*'],
 ['*', '*', 2, '*'],
 ['*', '*', '*', 3]]
np.array(transpose)
array([['2', '*', '*', '*'],
       ['*', '0', '*', '*'],
       ['*', '*', '2', '*'],
       ['*', '*', '*', '3']], dtype='<U11')

Method 06: Using .T attribute to acquire the transpose of a matrix in Python

Performing transposition tasks in Numpy makes it more flexible, and computationally easy to perform it. For that purpose, you need to import the Numpy library in your Python script. Then using np.array() function and .T transpose() function, perform the transpose task.

import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
print('Transpose of matrix A is: \n',A.T)
Transpose of matrix A is: 
 [[1 4 7]
 [2 5 8]
 [3 6 9]]

Conclusion

Transposing matrices is a task that is as easy as many other matrix operations. In this article, we have learned how to perform the transpose of a matrix in Python. The Pythonic Solution discussed here on this page with examples can be applied to any size matrix. 

Leave a Comment

Your email address will not be published. Required fields are marked *