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 Python 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]
Python Program to Sort Array in Descending Order using the For Loop.
In this Python 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.
# 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 Python Numpy Array items in Descending order using a for loop output
***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 Python 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)