How to reverse array in Numpy?

Let’s learn how to reverse an array in the Numpy Python library. We will check a few methods and tricks.
Numpy reverse array left right direction

Numpy Flip

The easiest way to reverse an array in Numpy is just to use the flip 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}")

reversed_array = np.flip(my_array)
print(f"This is reversed array: \n{reversed_array}")

Numpy how to reverse array

The array just got reversed.

Numpy Flipud

However, there are other ways to reverse an array. To reverse an array in the up-down direction specifically, you can use the dedicated Numpy flipud 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}")

reverse_array_up_down = np.flipud(my_array)
print(f"Array reversed in up/down direction: \n{reverse_array_up_down}")

Numpy reverse array up down direction

As shown, the array is reversed distinctly from the previous method by flipping in the up/down direction, offering utility in specific use cases.

See also  How to add dimension to Numpy array?

[::-1]

With this simple Python trick, there is also the possibility to do the same without 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}")

flipped_array = my_array[::-1]
print(f"Array reversed in up/down direction without Numpy function: \n{flipped_array}")

Python reverse array up down direction

The result is identical. Using my_array[::-1] effectively reverses the array in the up-down direction by creating a view, not a copy, of the array.

See also  How to Calculate the Determinant of a Matrix in Numpy

Numpy Fliplr

The same is possible in the left-to-right direction, of course. Fliplr is the name of a Numpy 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}")

flipped_array = np.fliplr(my_array)
print(f"Array reversed in left/right direction:  \n{flipped_array}")

Numpy reverse array left right direction

The array was flipped from left to right.

See also  How to Flatten an Array in NumPy

Knowing all of these methods, you can flip arrays according to your needs.