Python

NumPy np.flip()

The flip function in NumPy allows you to reverse the order of elements in an array along a specified axis while preserving the array’s shape.

Let us explore how this function works and how to use it.

Function Syntax

The function syntax is as depicted below:

numpy.flip(m, axis=None)

Parameters

The function accepts the following parameters:

  1. m – refers to the input array or array_like object.
  2. 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
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:

[[0 1 2]
 [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:

arr = np.arange(6).reshape(2,3)
print(f"original: {arr}")
print(f"flipped: {np.flip(arr, axis=0)}")

The code above should return the flipped array as:

original:
[[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:

arr = np.arange(6).reshape(2,3)
print(f"original: {arr}")
print(f"flipped: {np.flip(arr, axis=1)}")

The resulting output is as shown:

original:
[[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!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list