Let’s learn how to reverse an array in the Numpy Python library. We will check a few methods and tricks.
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}")
The array just got reversed.
However, there are other ways to reverse an array. This is how you reverse an array in the up-down direction. There is a dedicated Numpy flipud function for that.
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}")
As you can see, the array just got reversed and looks way different than the previous flip. This flipped array worked in an up/down direction, which can be useful in some use cases.
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}")
As you can see, the result is the same. my_array [::-1] simply created an array view in the up-down direction, as expected.
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}")
The array was flipped from left to right.
Knowing all of these methods, you can flip arrays according to your needs.