Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 it looks like after the transpose.
Let's say you have original matrix something like ?
matrix = [[1,2],[3,4],[5,6]] print(matrix)
[[1, 2], [3, 4], [5, 6]]
In above matrix we have two columns, containing 1, 3, 5 and 2, 4, 6.
So when we transpose above matrix, the columns becomes the rows. So the transposed version would look something like ?
[[1, 3, 5], [2, 4, 6]]
Below are several ways to accomplish matrix transpose in Python ?
Method 1 ? Using Nested Loops
The traditional approach using loops to iterate through rows and columns ?
# Original Matrix
matrix = [[1,2],[3,4],[5,6]]
# Create empty result matrix with swapped dimensions
result = [[0, 0, 0], [0, 0, 0]]
# Iterate through rows
for i in range(len(matrix)):
# Iterate through columns
for j in range(len(matrix[0])):
result[j][i] = matrix[i][j]
for row in result:
print(row)
[1, 3, 5] [2, 4, 6]
Method 2 ? Using List Comprehension
A more Pythonic approach using nested list comprehension ?
# Original Matrix
matrix = [[1,2],[3,4],[5,6]]
result = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
for row in result:
print(row)
[1, 3, 5] [2, 4, 6]
Method 3 ? Using zip() Function
The most elegant solution using zip() with unpacking operator ?
# Original Matrix
matrix = [[1,2],[3,4],[5,6]]
result = list(map(list, zip(*matrix)))
for row in result:
print(row)
[1, 3, 5] [2, 4, 6]
Method 4 ? Using NumPy Library
NumPy provides the most efficient way for matrix operations ?
import numpy as np # Original Matrix matrix = [[1,2],[3,4],[5,6]] result = np.transpose(matrix) print(result)
[[1 3 5] [2 4 6]]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Nested Loops | High | Slow | Learning/Understanding |
| List Comprehension | Medium | Medium | Pure Python solutions |
| zip(*matrix) | High | Fast | Small matrices |
| NumPy | High | Fastest | Large matrices |
Conclusion
Use zip(*matrix) for simple Python matrix transpose. For large matrices or mathematical operations, NumPy's transpose() provides the best performance and functionality.
