np.sort/argsort
sort orders values and argsort tells you the positions that would sort them.
In this page:
Syntax
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
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
- Forgetting arr.sort() returns None
- Using sort when you need indices
- 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: