Let us explore how this function works and how to use it.
Function Syntax
The function syntax is as depicted below:
Parameters
The function accepts the following parameters:
- m – refers to the input array or array_like object.
- axis – defines the axis along which the elements are reversed. By default, the function will flatten the array and reverse the elements.
Return Value
The function will return the array of m with the elements reversed but the shape preserved.
Example #1
The below code uses the flip() function to reverse the provided array.
import numpy as np
arr = np.arange(6).reshape(2,3)
print(arr)
print(np.flip(arr, axis=None))
In the example above, we reverse the elements of the 2d array. The resulting array is as shown:
[3 4 5]]
[[5 4 3]
[2 1 0]]
Example #2
To flip the array horizontally, we set the axis to zero, as shown in the code below:
print(f"original: {arr}")
print(f"flipped: {np.flip(arr, axis=0)}")
The code above should return the flipped array as:
[[0 1 2]
[3 4 5]]
flipped:
[[3 4 5]
[0 1 2]]
Example #3
To reverse the elements vertically, set the axis as one. The code illustration is as shown:
print(f"original: {arr}")
print(f"flipped: {np.flip(arr, axis=1)}")
The resulting output is as shown:
[[0 1 2]
[3 4 5]]
flipped:
[[2 1 0]
[5 4 3]]
Conclusion
In this tutorial, we have covered the syntax of the flip() function and saw detailed examples of how the function works along various array axes.
Thanks for reading!!