← Back to NumPy Course | Chapter 8: Statistics | Lesson 6 of 6

np.sort/argsort

sort orders values and argsort tells you the positions that would sort them.

In this page:

  1. np.sort/argsort
Syntax
python
sorted_arr = np.sort(arr)
indices = np.argsort(arr)
arr.sort()    # in place

np.sort/argsort

np.sort returns a sorted copy while arr.sort() sorts in place. argsort returns the indices that would sort the array, letting you reorder a second array to match. On 2-D data, axis chooses which direction to sort.

Note: Use argsort()[::-1] for descending order.

Example: np.sort/argsort

python
import numpy as np

names = np.array(["Ann", "Bob", "Cy"])
scores = np.array([88, 95, 70])
order = np.argsort(scores)[::-1]
print(np.sort(scores))
print(order)
print(names[order])

# Output:
# [70 88 95]
# [1 0 2]
# ['Bob' 'Ann' 'Cy']
Related Topics
Common Mistakes
  1. Forgetting arr.sort() returns None
  2. Using sort when you need indices
  3. Sorting the wrong axis
Chapter Summary
  • np.sort returns a copy
  • arr.sort sorts in place
  • argsort returns indices
  • Reverse with [::-1]
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.