
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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]]
- Related Articles
- How to Transpose a Matrix using Python?
- Find the transpose of a matrix in Python Program
- Transpose a matrix in Java
- Transpose a matrix in C#
- How to Transpose a matrix in Single line in Python?
- Compute a matrix transpose with Einstein summation convention in Python
- Python Program to find the transpose of a matrix
- Program to find the transpose of given matrix in Python
- Java program to transpose a matrix.
- C++ Program to Find Transpose of a Matrix
- Java Program to Find Transpose of a Matrix
- Java program to print the transpose of a matrix
- C++ Program to Find Transpose of a Graph Matrix
- Golang Program To Find The Transpose Of A Matrix
- How to calculate transpose of a matrix using C program?
