How to rotate a matrix with Numpy

Let’s explore how to efficiently rotate a matrix in Numpy, where we’ll uncover some clever tricks along the way.

Numpy rotate over axes

Rotating by 90 Degrees

Rotating a matrix by 90 degrees using Numpy is straightforward with the dedicated rot90 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}")

Numpy how to rotate array

Rotating by 270 Degrees

To perform a 270-degree rotation (equivalent to three rounds of 90-degree rotation counterclockwise), simply pass 3 as a parameter to the rot90 function:

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}")

Numpy array rotate 270 degrees

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.

See also  How to convert numpy to xyz file?

Rotating by 180 Degrees

For a 180-degree rotation, use np.rot90(my_array, 2). Note that applying np.rot90(my_array, 4) will not alter the array.

You can also rotate the array over specific 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}")

Numpy rotate over axes

I used np.rot90(my_array, axes=(1, 0)) and this is how it got rotated.

See also  How to sum up array in Numpy?

In addition to rotating matrices, you can also flip them horizontally and vertically with Numpy. Here’s how:

Horizontal Flip

To flip a matrix horizontally, use np.fliplr():

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}")

horizontal_flip = np.fliplr(my_array)
print(f"Array after horizontal flip: \n{horizontal_flip}")

Vertical Flip

For a vertical flip, employ np.flipud():

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}")

vertical_flip = np.flipud(my_array)
print(f"Array after vertical flip: \n{vertical_flip}")

These simple Numpy functions allow you to achieve horizontal and vertical flips effortlessly, offering versatile options for manipulating matrices.

See also  How to create numpy array with zeros?