How to Transpose Matrix Python
A “Matrix” is a 2-dimensional array of numbers organized into rows and columns and “Transposing a Matrix” is a common operation in data analysis and linear algebra. Transposing a matrix means flipping it over its main diagonal so that the rows become columns and vice versa. There are various benefits of transposing a matrix such as simplifying calculations, changing the perspective of a problem, or preparing data for machine learning algorithms.
This blog post presents the approaches to transposing a matrix in Python using different methods and libraries.
How to Transpose a Matrix in Python?
The below-given approaches are used to transpose the specified matrix in Python:
Method 1: Transpose a Matrix Using “numpy.transpose()” Method
The “numpy.transpose()” method returns an array with transposed axes. It is such that a “2-D” array can be transposed, but a “1-D” array cannot. This method is equivalent to the numpy “ndarray.transpose()” method.
Syntax
In the above syntax, the “a” parameter is the initialized array, and the “axes” parameter specifies how the axes are permuted.
Example
The below example code is utilized to transpose a matrix:
mtrx = numpy.array([[2, 4, 8], [1, 3, 7]])
print('Original Matrix:\n', mtrx)
print('\nTransposed Matrix:\n', mtrx.transpose())
In the above code, the “numpy.array()” function is used to create a matrix array with three rows and three columns. The “matrix.transpose()” method is used to return the transpose of the provided matrix.
Output
Based on this snippet, it is verified that the transpose of the original matrix has been calculated.
Method 2: Transpose a Matrix Using a Nested “for” Loop
The nested “for” loop can also be used to transpose a matrix in Python by iterating over the rows and columns of the input matrix.
Example
In the below code, the nested “for” loop is utilized to transpose a matrix:
mtrx = numpy.array([[1, 2, 3], [4, 5, 6]])
print('Given Matrix:\n', mtrx)
transposed_mtrx = numpy.zeros((mtrx.shape[1], mtrx.shape[0]))
for i in range(mtrx.shape[0]):
for j in range(mtrx.shape[1]):
transposed_mtrx[j, i] = mtrx[i, j]
print('\nTranspose Matrix:\n', transposed_mtrx)
In the above code block:
- The “numpy” library is imported and the matrix is initialized (having two rows and three columns) using the “array()” function.
- The “zeros()” function creates a new NumPy array called “transposed_mtrx”. This array is initialized to all zeros.
- The nested “for” loop is utilized to loop over the rows and columns of the provided matrix.
- The value of “mtrx[i, j]” is assigned to “transposed_mtrx[j, i]” which swaps the rows and columns of the element in the input matrix, thereby computing its transpose.
Output
Here, it can be analyzed that the transpose of the defined array is returned with the changed dimensions i.e., the resultant matrix comprising three rows and two columns.
Method 3: Transpose a Matrix Utilizing Nested “List Comprehension”
A nested list comprehension is employed to create a new list from a list of lists.
Syntax
In the above syntax, the “expression” is evaluated for each element in the “outer list”, and the result is added to the “new list”. The “inner_list” is evaluated for each element in the “outer list”, and the result is used to evaluate the expression.
Example
Here is a code that is utilized to transpose a matrix:
print('Given Matrix:/n', mtrx)
transp_mtrx = [[mtrx[j][i] for j in range(len(mtrx))] for i in range(len(mtrx[0]))]
print('Transpose Matrix:', transp_mtrx)
In the above code:
- A matrix is created with two rows and three columns.
- The new matrix named “transp_mtrx” is created using the nested “List Comprehension”.
- In the nested “List Comprehension”, the outer list comprehension iterates over the rows of the initialized matrix and the inner list comprehension iterates over the columns of the input matrix.
- The nested list comprehension returns a new list by swapping the rows and columns of the element in the given matrix.
Output
In this snippet, the transpose of the matrix has been returned.
Method 4: Transpose a Matrix Utilizing the “zip()” Function
The “zip()” function creates a single iterable with tuples of matching elements from two or a number of iterables such as dictionaries, lists, or tuples. This can also be used to transpose a matrix in Python.
Syntax
In the above syntax, the “*iterables” are any type of iterable objects, such as files, lists, tuples, etc.
Example
Let’s utilize the following code to transpose a matrix:
print('Given Matrix:/n', mtrx)
transp_mtrx = list(zip(*mtrx))
print('Transpose Matrix:', transp_mtrx)
According to the above code snippet:
- The “zip()” function is used to transpose the matrix by taking the “* operator” with the matrix as its arguments.
- The “* operator” unpacks the input matrix into individual arguments for the zip function.
- The return value of the “zip()” function is a list of tuples, which is then converted to a list using the “list()” function.
Output
In the above output, the transpose of the matrix has been determined.
Conclusion
The “numpy.transpose()” method, nested “for” loop, nested “List Comprehension”, or the “zip()” function is used to transpose the input matrix in Python. The “numpy.transpose()” method is the simplest that returns the transpose directly. This Python guide delivered multiple ways to transpose a matrix using numerous examples.
Source: linuxhint.com