Python

NumPy Np.Rot90()

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:

  1. array – refers to the input array.
  2. k – Number of times to rotate the array by 90 degrees.
  3. 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!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list