argsort & Ranking
argsort returns the INDICES that would sort an array — the key to ranking players, sorting one array by another, and finding positions with argmax/argmin.
np.sort tells you the sorted runs: [580 643 695 710 779]. But the coach asks: who scored them? The names live in a different array. Sorting the runs alone loses the link. argsort solves this: instead of sorted values, it gives you the positions in sorted order — and those positions work on any array that lines up with the original.
Definition
np.argsort(a)returns an array of indices that would sortain ascending order:a[np.argsort(a)]equalsnp.sort(a). Because they are indices, the same order can be applied to any parallel array (names, teams, balls faced) to keep the data aligned.
- Indices, not values — the first number is the index of the smallest element, the second is the index of the next smallest, and so on.
- Parallel arrays — arrays where position
idescribes the same thing (playeri). Indexing them all with the same argsort result keeps every row of information together. - "arg" functions —
argsort,argmax,argmin,argpartition,argwhere: theargprefix always means "give me positions, not values".
Syntax
python
np.argsort(a, axis=-1, kind=None, order=None, *, stable=None)
a.argsort(axis=-1, kind=None, order=None)
np.argmax(a, axis=None) # index of the largest value
np.argmin(a, axis=None) # index of the smallest value| Parameter | Meaning | Default |
|---|---|---|
a | array to compute the sorting order of | required |
axis | axis to sort along (None = flattened) | -1 (argsort), None (argmax/argmin) |
kind | sorting algorithm; "stable" keeps ties in original order | None |
stable | True = same as kind="stable" | None |
Example — rank players by runs
python
import numpy as np
players = np.array(["Virat", "Rohit", "Hardik", "Shubman", "Shreyas"])
runs = np.array([779, 710, 580, 643, 695])
idx = np.argsort(runs)
print(idx)
print(runs[idx])
print(players[idx])text
[2 3 4 1 0]
[580 643 695 710 779]
['Hardik' 'Shubman' 'Shreyas' 'Rohit' 'Virat']How it works:
text
index: 0 1 2 3 4
runs: 779 710 580 643 695
smallest is at index 2 (580), then 3 (643), then 4 (695), then 1 (710), then 0 (779)
argsort -> [2 3 4 1 0]Using the same idx on players puts the names in the same order as the runs.
Example — leaderboard, highest first
python
order = np.argsort(runs)[::-1]
print(order)
print(players[order])
print(runs[order])
for rank, i in enumerate(order, start=1):
print(rank, players[i], runs[i])text
[0 1 4 3 2]
['Virat' 'Rohit' 'Shreyas' 'Shubman' 'Hardik']
[779 710 695 643 580]
1 Virat 779
2 Rohit 710
3 Shreyas 695
4 Shubman 643
5 Hardik 580np.argsort(-runs) gives the same [0 1 4 3 2] for numeric data.
Example — each player's rank number
order says "who is 1st, 2nd, 3rd…". Sometimes you need the reverse: "what rank did each player get?" (in the original order).
python
ranks = np.empty_like(order)
ranks[order] = np.arange(1, len(runs) + 1)
print(ranks)text
[1 2 5 4 3]Virat is 1st, Rohit 2nd, Hardik 5th, Shubman 4th, Shreyas 3rd. (A shortcut for 0-based ascending ranks is runs.argsort().argsort() → [4 3 0 1 2].)
Ties and stable sorting
python
pts = np.array([16, 18, 16, 14, 18])
teams = np.array(["CSK", "MI", "RCB", "KKR", "GT"])
print(np.argsort(pts, kind="stable"))
print(teams[np.argsort(-pts, kind="stable")])text
[3 0 2 1 4]
['MI' 'GT' 'CSK' 'RCB' 'KKR']With kind="stable", teams on equal points keep their original order (CSK before RCB, MI before GT). Note np.argsort(pts)[::-1] would reverse tied teams too — use np.argsort(-pts, kind="stable") when tie order matters.
Sorting by two keys — np.lexsort (bonus)
The points table sorts by points, then by net run rate. np.lexsort takes keys with the primary key last:
python
nrr = np.array([0.5, 0.8, 0.9, -0.1, 0.2])
idx = np.lexsort((-nrr, -pts)) # primary: points (desc), then NRR (desc)
print(teams[idx], pts[idx], nrr[idx])text
['MI' 'GT' 'RCB' 'CSK' 'KKR'] [18 18 16 16 14] [ 0.8 0.2 0.9 0.5 -0.1]argmax and argmin
python
print(runs.argmax(), players[runs.argmax()], runs.argmin())text
0 Virat 2argmax = index of the top scorer (Virat, index 0); argmin = index of the lowest (Hardik, index 2). On a 2D array without axis, they return a flat index — convert it with np.unravel_index(i, a.shape).
argsort on 2D arrays
python
squad = np.array([[72, 45, 88, 31],
[56, 0, 74, 88],
[45, 32, 0, 67]])
print(np.argsort(squad, axis=1))text
[[3 1 0 2]
[1 0 2 3]
[2 1 0 3]]Row 0: Virat's lowest score was in match index 3 (31), his highest in match index 2 (88).
Comparison
| Function | Returns | Example on [779, 710, 580] |
|---|---|---|
np.sort | sorted values | [580 710 779] |
np.argsort | indices that sort | [2 1 0] |
np.argmax | index of max | 0 |
np.argmin | index of min | 2 |
Common mistakes
- ❌ Sorting
runsandplayersseparately withnp.sort— the names get sorted alphabetically and no longer match the runs. ✅order = np.argsort(runs); thenplayers[order],runs[order]. - ❌ Reading
argsortoutput as ranks. ✅argsortsays who is in each position; ranks need the inverse (ranks[order] = ...). - ❌ Forgetting
[::-1]for "highest first".
Interview tip
Q: How do you sort the rows of a 2D array by its second column?
A: arr[arr[:, 1].argsort()] — argsort the column to get a row order, then index the rows with it. Each row stays intact.
Key points to remember
- np.argsort returns the INDICES that would sort an array: a[np.argsort(a)] == np.sort(a).
- Apply the same argsort result to parallel arrays (names, teams) to keep data aligned.
- Highest first: np.argsort(a)[::-1], or np.argsort(-a, kind='stable') to keep tie order.
- argsort gives 'who is at each position'; ranks per item need the inverse: ranks[order] = np.arange(1, n+1).
- argmax / argmin return the index of the largest / smallest value (flat index unless axis is given).
- Sort table rows by one column with arr[arr[:, k].argsort()]; use np.lexsort for multiple keys (primary key last).
Try it yourself
Leaderboard with argsort
Sort table rows by one column
Each player's rank number
Practice: rank by strike rate
Revision Flashcards
Tap a card to flip it and see the answer.
