Can we sort Numpy arrays in reverse order?


#1

Question

In the context of this exercise, can we sort Numpy arrays in reverse order?

Answer

In Numpy, the np.sort() function does not allow us to sort an array in descending order. Instead, we can reverse an array utilizing list slicing in Python, after it has been sorted in ascending order.

Example

array = np.array([7, 5, 3, 2, 6, 1, 4])

# Sort in ascending order
sorted_array = np.sort(array)
# [1, 2, 3, 4, 5, 6, 7]

# Reverse the sorted array
reverse_array = sorted_array[::-1]
# [7, 6, 5, 4, 3, 2, 1]