To reverse the order of array elements in Python, use the numpy flip() method.
np.flip
The np.flip() method is used to reverse the order of array elements by keeping the shape of the array along a specified axis. The numpy flip() method accepts the array and axis as arguments and returns the array while preserving the shape of the array.
Syntax
numpy.flip(array, axis( axis on which array is to be reversed))
Parameters
The flip() function takes two parameters.
The first parameter is an array that takes the input array; the second parameter is the axis on which the array can be reversed.
Return Value
The flip() function returns the reversed array while preserving its shape.
How to reverse an array in Python.
To reverse a numpy array, use the np.flip() function. The np.flip() reverses the order of items in the array along the given axis. The shape of an array is preserved, but the items are reordered.
See the following code.
import numpy as np arr = np.arange(8).reshape((2, 2, 2)) print("Input array: ", arr) print("\nOutput array: ", np.flip(arr, 0))
Output
Input array: [[[0 1] [2 3]] [[4 5] [6 7]]] Output array: [[[4, 5] [6, 7]] [0, 1] [2, 3]]]
In this example, we can see that we have rearranged the array by preserving its shape.
Write a program to flip a 2×2 array and print its output.
import numpy as np arr = np.arange(4).reshape((2, 2)) print("Input array: ", arr) print("\nOutput array: ", np.flip(arr, 0))
Output
Input array: [[0 1] [2 3]] Output array: [[2 3] [0 1]]
In this example, we have taken a 2×2 matrix, and elements are flipped in the output array.
Conclusion
Using numpy.flip() function, you can flip the NumPy array ndarray vertically (up / down) or horizontally (left / right). There are also numpy.flipud() specialized for vertical flipping and numpy.fliplr() specialized for horizontal flipping.