Let’s learn how to rotate a matrix in Numpy. We are going to see a few tricks in that matter.
Rotation by 90 degrees
With Numpy it is very easy to rotate matrix 90 degrees. There is dedicated rot90 Numpy method.
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array) print(f"Array rotated: \n{rotate_array}")
Rotation by 270 degrees
To rotate 270 degrees just add 3 as a parameter to rot90 function. This parameter makes 3 rounds of 90 degrees rotation (counter clockwise).
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array, 3) print(f"Array rotated 270 degrees: \n{rotate_array}")
This is 270 degrees rotation but we can also say that this is left rotation because this is how to rotate an matrix left direction.
Rotation by 180 degrees
To rotate 180 put np.rot90(my_array, 2). Having np.rot90(my_array, 4) will not change the array at all.
You can also rotate an array over the axes.
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array, axes=(1, 0)) print(f"Array rotated over axes=(1, 0): \n{rotate_array}")
I used np.rot90(my_array, axes=(1, 0)) and this is how it got rotated.