numpy.flip(): Reverse the Order of Elements in Array – NumPy Tutorial

By | August 10, 2022

In this tutorial, we will use some examples to show you how to use numpy.flip() function correctly. There is an important thing you must concern.

numpy.flip()

It is defined as:

numpy.flip(m, axis=None)

It will reverse the order of elements in an array along the given axis.

Notice

This function only reverse the order of elements in an array, however, it does not sort elements in this array.

How to use numpy.flip()?

Here are some examples:

import numpy as np

data = np.random.random([3,4])
print(data)
x = np.flip(data, axis = 1)
print(x)

Run this code, we will see:

[[3.37347712e-01 9.80788407e-01 9.68002832e-01 5.78279577e-01]
 [4.25048577e-01 5.04030538e-01 7.51026337e-01 9.74105023e-01]
 [3.00294928e-05 1.76681655e-02 2.27272336e-01 3.35350512e-01]]
[[5.78279577e-01 9.68002832e-01 9.80788407e-01 3.37347712e-01]
 [9.74105023e-01 7.51026337e-01 5.04030538e-01 4.25048577e-01]
 [3.35350512e-01 2.27272336e-01 1.76681655e-02 3.00294928e-05]]

Comparing elements in data and x, we can find:

understand numpy.flip() with examples

Reverse the order of  elements to create x along axis = 1 in data. However, these elements are not sorted.

x = np.flip(data, axis = 0)
print(x)

We will see:

[[3.00294928e-05 1.76681655e-02 2.27272336e-01 3.35350512e-01]
 [4.25048577e-01 5.04030538e-01 7.51026337e-01 9.74105023e-01]
 [3.37347712e-01 9.80788407e-01 9.68002832e-01 5.78279577e-01]]

Elements are reversed along axis = 0 in data.

Leave a Reply