There are three methods to reverse NumPy array. We will discuss all of them here.
Here we are using only NumPy libraries. That’s why I am importing it using the import statement.
import numpy as np
Now for the demonstration purpose lets we create a Numpy array. It will be of both single and multiple dimensions.
One Dimensional Array
array_1d = np.array([10,30,40,20])
Two Dimensional Array
array_2d = np.array([[10,30],[60,50]])
Let’s reverse all the NumPy array I have created in step 2.
The shortcut method to reverse the NumPy array is to use the slicing method. Use the below code.
For 1-D Array
array_1d[::-1]
2 -D Array
array_2d[::-1]
Output
The numpy.flip() accepts two arguments. One is the array you want to flip. The second the axis value 0,1 or None. It is very useful if you want to flip some specific columns or rows.
For 1-D Array
np.flip(array_1d)
2 -D Array
np.flip(array_2d)
Output
The third method for reversing the NumPy array is the numpy.flipud() method.
For 1-D Array
np.flipud(array_1d)
2 -D Array
To demonstrate for two-dimensional array, let’s create a diagonal matrix using the numpy.diag() method. I have not used the above 2D example here because the diagonal matrix clearly shows where the flipping has been done.
diagonal_matrix = np.diag([10,20,30])
Now pass it inside the np.flipud() method as an argument. It will Flip an array vertically (axis=0).
np.flipud(diagonal_matrix)
You will get the following output.
Now the last method to reverse the NumPy array is the numpy.fliplr() method. It will Flip an array horizontally (axis=1). There is only one condition for using it. The NumPy array should be a 2 or N-dimensional array. I am using the same diagonal matrix used in method 3.
Execute the following line of code.
np.fliplr(diagonal_matrix)
Output
These are the methods for reversing the NumPy array. Methods 1,2 and 3 works on both single and multi-dimensional array. But the last method 4 works on only multi-dimensional array.
Hope you have liked this tutorial. Even if you have any query then you can contact us for more info.
Source of tutorial