All lessons

Module 2: Selecting and filtering · Lesson 2.4 · about 15 min

Sorting and top-N

Sort by one or several columns, ascending or descending, find the top or bottom N with nlargest and nsmallest, rank values, and reset the index after sorting.

Key points, meanings and formulas on one page: choose "Save as PDF" in the print box.

Module 2 · about 15 minutes · uses Lesson 2.3. You’ll be able to sort tables and pull out top and bottom N.

sort_values puts rows in order by one or more columns, and nlargest and nsmallest jump straight to the top or bottom N.

In everyday terms: sorting a deck of cards by suit and then by number within each suit: the first key decides, the second breaks ties.

1. sort_values

Pythonproducts.csv

The second sort orders categories A to Z, and within each category the most expensive first.

2. Top and bottom N

Pythonproducts.csv

nlargest is shorter and faster than sorting the whole table when you only need a few rows.

Top N within each group combines sorting with groupby (Module 4):

Pythonproducts.csv

3. Ranks and a clean index

Pythonproducts.csv

method='min' gives tied values the same (best) rank, like a sports table. reset_index(drop=True) renumbers rows 0, 1, 2 in the new order.

sort_values('qty', ascending=False)
Biggest first.
sort_values(['store', 'qty'])
By store, then by qty within store.
nlargest(5, 'qty')
The 5 biggest rows, quickly.
rank()
Each value's place in the order.
Physical meaning
Sorting changes the order of rows but keeps their labels. That is why reset_index(drop=True) is often the next step, to number the sorted rows 0, 1, 2 again.

“Sorting by two columns sorts each one separately.” It sorts by the first, and uses the second only to order rows that tie on the first.

Watch it happen, one step at a time:

Start.
storeqty
WEB2
S015
S011
WEB4
Sort by store. S01, S01, WEB, WEB.
Then by qty, biggest first. sort_values(['store', 'qty'], ascending=[True, False])
Result.
storeqty
S015
S011
WEB4
WEB2

4. Your turn

Your turncustomers.csv
Your turnproducts.csv
How it works

Principle: sorting reorders rows but keeps each row’s label, so you can always trace a row back. Missing values go last by default (na_position='first' to change it).

Stable sorts: to sort by A within B, either sort by [B, A] in one call, or sort by A then by B with kind='stable', which keeps the earlier order among ties.

5. Practice

  1. The 10 cheapest products?
  2. Products from most to least margin (price − cost)?
  3. What does rank(method='dense') do differently from 'min'?
Answers
  1. products.nsmallest(10, 'price').
  2. products.assign(margin=products['price'] - products['cost']).sort_values('margin', ascending=False).
  3. Dense ranks leave no gaps after ties (1, 2, 2, 3) where 'min' skips (1, 2, 2, 4).

New words: sort_values, ascending, nlargest, nsmallest, rank, reset_index.

  • sort_values sorts by one or more columns; ascending can be a list.
  • nlargest / nsmallest find the top or bottom N fast.
  • rank gives positions; method= decides how ties are handled.
  • reset_index(drop=True) renumbers rows after sorting.

Check yourself

1How do you sort by store, then by qty from high to low?
2What does df.nlargest(5, "qty") return?
3Why use reset_index(drop=True) after sorting?

Sources

Your ticks stay in this browser. Save them as a file on the course home.

Updated 2026-11-22. All datasets are made up. Python runs in your browser (the first run downloads it once, about 20 MB); nothing you type is sent anywhere.