1

I am just wondering how to sort a NumPy array in descending order using NumPy sort() function efficiently. I checked the NumPy official documentation and StackOverflow question but I couldn`t able to find how to sort a NumPy array in descending order using the NumPy sort().

For instance:

import numpy as np
arr=np.array([1,5,8,4,5])
arr.sort()
print(arr)

Output:

[1,4,5,5,8]

I want to sort it by descending order, I understand after sorting the array in ascending order, I can reverse it like below.

arr.sort()[::-1]

But it creates a new array, Is it possible to sort descending without approaching this method?

2
  • basically you want to reverse the array first and then sort arr[::-1].sort() Commented Apr 3, 2019 at 13:40
  • Flipping with [::-1] creates a view, not a copy. Commented Apr 3, 2019 at 13:45

1 Answer 1

3

Using -np.sort(-arr):

import numpy as np
arr=np.array([1,5,8,4,5])
print(-np.sort(-arr))

OUTPUT:

[8 5 5 4 1]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.