The NumPy rot90() function allows the rotating of an array by 90 degrees along a specified axis.
Let us discuss.
Function Syntax
The function syntax is as shown:
1 | numpy.rot90(array, k = 1, axes = (0, 1)) |
The function parameters are as shown:
- array – refers to the input array.
- k – Number of times to rotate the array by 90 degrees.
- axis – along which axis to rotate the array.
Return Value
The function returns a copy of the array with the elements rotated along the specified axis by 90 degrees.
Example #1
The example below shows using the rot90() function with a two-dimensional array.
1 2 3 4 | # import numpy import numpy as np arr = np.array([[1,2,3], [5,6,7]]) print(np.rot90(arr)) |
The function will rotate the array along the zero axis and return the array as shown:
1 2 3 | [[3 7] [2 6] [1 5]] |
Example #2
To rotate an array along the zero axis by 180 degrees, we can do:
1 2 | arr = np.array([[1,2,3], [5,6,7]]) print(np.rot90(arr, k=2)) |
The number of times tells the function to rotate the array along the zero axis by 180 degrees. The above code should return an array as:
1 2 | [[7 6 5] [3 2 1]] |
Conclusion
This article covered how to rotate an array by 90 degrees along a specified axis using the rot90() function.
Thanks for reading!!