Let’s learn how to reverse an array in the Numpy Python library. We will check a few methods and tricks.
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}")
The array just got reversed.
Numpy Flipud
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.
[::-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}")
As you can see, the result is the same. my_array [::-1] simply created an array view in the up-down direction, as expected.
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}")
The array was flipped from left to right.
Knowing all of these methods, you can flip arrays according to your needs.
Key Takeaways
- There are three ways to reverse an array in Numpy:
- Using the `flip()` function
- Using the `flipud()` function
- Using the `[::-1]` slicing syntax
FAQ
- Q: Which method is the best to reverse an array?
- A: The best method to use depends on your specific needs. If you need to reverse the array in both directions, then the `flip()` function is the best option. If you only need to reverse the array in one direction, then the `flipud()` or `[::-1]` slicing syntax can be used.
- Q: How do I reverse an array in a specific direction?
- To reverse an array in a specific direction, you can use the `flip()` function and specify the axis that you want to reverse.