How to Reverse Array in NumPy (np.flip, np.flipud, np.fliplr, and Slicing Examples)

Let’s learn how to reverse array in NumPy using np.flip() for all axes, np.flipud() for vertical reversal, np.fliplr() for horizontal reversal, and slicing tricks.

Numpy reverse array left right direction

How to Reverse Arrays with Numpy Flip

NumPy’s np.flip() provides the easiest way to reverse array in NumPy along any axis, while np.flipud() and np.fliplr() offer specialized vertical and horizontal flipping for 2D arrays.

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.

See also  How to you find the cumulative sum in Python?

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 shuffle an array in Numpy?

[::-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 Convert Numpy Array to Boolean Value

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.

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