Write a Python Program to sort Numpy Array items in Descending order. First, the Numpy sort function (orarr.sort()) sorts the array items in ascending order. Next, we sliced the array using negative values to reverse the array (descarr = orarr[::-1]), which becomes descending.
# Sort Array Descending
import numpy as np
orarr = np.array([22, 98, 77, 88, 35, 15, 122, 91])
print("***Sorting Numpy Array in Descending Order***")
print("Original Array = ", orarr)
orarr.sort()
descarr = orarr[::-1]
print("Array in Descending Order = ", descarr)
Sort Numpy Array items in Descending order output.
***Sorting Numpy Array in Descending Order***
Original Array = [ 22 98 77 88 35 15 122 91]
Array in Descending Order = [122 98 91 88 77 35 22 15]
This program uses the NumPy module’s built-in sort() and flip() methods. Here, the sort() method sorts the array in ascending order, and the flip() method reverses it. Finally, we get the sorted array in descending order. Refer to Python sort.
import numpy as np
a = np.array([22, 98, 77, 88, 35, 15, 122, 91])
b = np.flip(np.sort(a))
print(b)
[122 98 91 88 77 35 22 15]
Python Program to Sort Array in Descending Order using the For Loop
In this example, we used the Nested for loop range to sort the numpy array items in Descending order. Within the loop, the if statement (if (dearr[i] < dearr[j])) checks each item is less than other array items and assigns them to the temp variable. Refer to Python array.
# Sort Array Descending
import numpy as np
dearr = np.array([11, 46, 22, 89, 77, 98, 55, 181, 65])
print("***Sorting Numpy Array in Descending Order***")
print("Original Array = ", dearr)
length = len(dearr)
for i in range(length):
for j in range(i + 1, length):
if (dearr[i] < dearr[j]):
temp = dearr[i]
dearr[i] = dearr[j]
dearr[j] = temp
print("Array in Descending Order = ", dearr)
Sort Numpy Array items in Descending order using a for loop output. For more examples, refer to the Python Basic Programs.
***Sorting Numpy Array in Descending Order***
Original Array = [ 11 46 22 89 77 98 55 181 65]
Array in Descending Order = [181 98 89 77 65 55 46 22 11]
In this NumPy array example, we created a function (arrayDescending(dearr)) that sorts the array elements in descending order.
# Sort Array Descending
import numpy as np
def arrayDescending(dearr):
for i in range(len(dearr)):
for j in range(i + 1, len(dearr)):
if (dearr[i] < dearr[j]):
temp = dearr[i]
dearr[i] = dearr[j]
dearr[j] = temp
dearr = np.array([64, 36, 77, 55, 88, 95, 44, 91, 21])
print("***Sorting Numpy Array in Descending Order***")
print("Original Array = ", dearr)
arrayDescending(dearr)
print("Array in Descending Order = ", dearr)

Also Read