How to reverse column order in a matrix with Python?
In this article, we will see how to reverse the column order of a matrix in Python.
Input: arr = [[10,20,30], [40,50,60], [70,80,90]] Output: 30 20 10 60 50 40 90 80 70 Input: arr = [[15,30], [45,60], [75,90], [105,120]] Output: 30 15 60 45 90 75 120 105
Matrices are created in python by using nested lists/arrays. However, a more efficient way to handle arrays in python is the NumPy library. To create arrays using NumPy use this or matrix in python once go through this.
- Iterate through each row
- For every row, use list comprehension to reverse the row (i.e. a[::-1])
- Append the reversed rows into a new matrix
- Print the matrix
An array object in NumPy is called ndarray, which is created using the array() function. To reverse column order in a matrix, we make use of the numpy.fliplr() method. The method flips the entries in each row in the left/right direction. Column data is preserved but appears in a different order than before.
Parameters: m (array_like) – Input array must be at least 2-D.
Returned Value: ndarray – A view of m is returned with the columns reversed, and this operation’s time complexity is O(1).
Flipped_arr contains a reversed column order matrix where the column order has changed from c1,c2,c3 to c3,c2,c1, and the elements of each column remain intact under their respective headers (c1,c2,c3).