
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Transpose a Matrix in Python
Transpose a matrix means we’re turning its columns into its rows. Let’s understand it by an example what if looks like after the transpose.
Let’s say you have original matrix something like -
x = [[1,2][3,4][5,6]]
In above matrix “x” we have two columns, containing 1, 3, 5 and 2, 4, 6.
So when we transpose above matrix “x”, the columns becomes the rows. So the transposed version of the matrix above would look something like -
x1 = [[1, 3, 5][2, 4, 6]]
So the we have another matrix ‘x1’, which is organized differently with different values in different places.
Below are couple of ways to accomplish this in python -
Method 1 - Matrix transpose using Nested Loop -
#Original Matrix x = [[1,2],[3,4],[5,6]] result = [[0, 0, 0], [0, 0, 0]] # Iterate through rows for i in range(len(x)): #Iterate through columns for j in range(len(x[0])): result[j][i] = x[i][j] for r in Result print(r)
Result
[1, 3, 5] [2, 4, 6]
Method 2 - Matrix transpose using Nested List Comprehension.
#Original Matrix x = [[1,2],[3,4],[5,6]] result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))] for r in Result print(r)
Result
[1, 3, 5] [2, 4, 6]
List comprehension allows us to write concise codes and should be used frequently in python.
Method 3 - Matrix Transpose using Zip
#Original Matrix x = [[1,2],[3,4],[5,6]] result = map(list, zip(*x)) for r in Result print(r)
Result
[1, 3, 5] [2, 4, 6]
Method 4 - Matrix transpose using numpy library Numpy library is an array-processing package built to efficiently manipulate large multi-dimensional array.
import numpy #Original Matrix x = [[1,2],[3,4],[5,6]] print(numpy.transpose(x))
Result
[[1 3 5] [2 4 6]]