![]() |
VOOZH | about |
Transposing a matrix in Python means flipping it over its diagonal, turning all the rows into columns and all the columns into rows. For example, a matrix like [[1, 2], [3, 4], [5, 6]], which has 3 rows and 2 columns, becomes [[1, 3, 5], [2, 4, 6]], which has 2 rows and 3 columns after transposing. Let's understand different methods to do this efficiently.
List comprehension is used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in a column-major manner and assign the result to the rez matrix which is the transpose of m.
[1, 3, 5] [2, 4, 6]
Explanation: This expression creates a new matrix by taking each column from the original as a row in the new one. It swaps rows with columns.
Python Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.
(1, 4, 7, 10) (2, 5, 8, 11) (3, 6, 9, 12)
Explanation: This code transposes the matrix m using zip(*m). The * unpacks the rows and zip() groups elements column-wise. Each output tuple represents a column from the original matrix, effectively swapping rows and columns.
Python NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays.
Example 1: The transpose method returns a transposed view of the passed multi-dimensional matrix.
[[1 4] [2 5] [3 6]]
Explanation: numpy.transpose() swap rows and columns of the matrix m. It converts the original matrix of 2 rows and 3 columns into one with 3 rows and 2 columns effectively transposing it.
Example 2: Using ".T" after the variable
[[1 4] [2 5] [3 6]]
Explanation: This code uses NumPy to create a 2D array m, then prints its transpose using .T. The .T attribute swaps rows and columns, converting the original 2x3 matrix into a 3x2 transposed matrix.
Python itertools is a module that provides various functions that work on iterators to produce complex iterators. chain() is a function that takes a series of iterables and returns one iterable.
[[1, 4], [2, 5], [3, 6]] Time taken 9813 ns
Explanation: It first converts the matrix to a list of lists, flattens it into a single list using chain(*M), then rebuilds the transposed matrix by slicing every n-th element.
Related articles: