We can not sort a numpy array in descending order directly. In this tutorial, we will introduce you how to do.
We can use numpy.sort() + numpy.flip() to implement it.
numpy.sort(): it will sort an array in ascending order.
It is defined as:
numpy.sort(a, axis=- 1, kind=None, order=None)
numpy.flip(): it will reverse the order of elements in an array.
numpy.flip(): Reverse the Order of Elements in Array – NumPy Tutorial
How to sort an array in descending order?
Here we will use an example to show you how to do.
import numpy as np data = np.random.random([3,4]) print(data) x = np.sort(data, axis = 1) print("in ascending order axis = 1:") print(x) x = np.flip(x, axis = 1) print("in descending order axis = 1:") print(x)
Run this code, we will see:
[[2.58593345e-01 4.92161837e-01 3.90792782e-01 5.54329892e-01] [6.03188609e-01 4.75686077e-01 5.71715299e-05 5.67659390e-01] [9.11993114e-01 2.63952876e-01 3.33518342e-01 5.09930498e-01]] in ascending order axis = 1: [[2.58593345e-01 3.90792782e-01 4.92161837e-01 5.54329892e-01] [5.71715299e-05 4.75686077e-01 5.67659390e-01 6.03188609e-01] [2.63952876e-01 3.33518342e-01 5.09930498e-01 9.11993114e-01]] in descending order axis = 1: [[5.54329892e-01 4.92161837e-01 3.90792782e-01 2.58593345e-01] [6.03188609e-01 5.67659390e-01 4.75686077e-01 5.71715299e-05] [9.11993114e-01 5.09930498e-01 3.33518342e-01 2.63952876e-01]]