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.
Module 2 · about 15 minutes · uses Lesson 2.3. You’ll be able to sort tables and pull out top and 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
The second sort orders categories A to Z, and within each category the most expensive first.
2. Top and bottom N
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):
3. Ranks and a clean index
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:
| store | qty |
|---|---|
| WEB | 2 |
| S01 | 5 |
| S01 | 1 |
| WEB | 4 |
sort_values(['store', 'qty'], ascending=[True, False])| store | qty |
|---|---|
| S01 | 5 |
| S01 | 1 |
| WEB | 4 |
| WEB | 2 |
4. Your turn
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
- The 10 cheapest products?
- Products from most to least margin (price − cost)?
- What does
rank(method='dense')do differently from'min'?
Answers
products.nsmallest(10, 'price').products.assign(margin=products['price'] - products['cost']).sort_values('margin', ascending=False).- 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
Sources
- pandas documentation, User Guide: Essential basic functionality (sorting) https://pandas.pydata.org/docs/user_guide/basics.html#sorting
- McKinney, W. (2022), Python for Data Analysis, 3rd edition, O'Reilly (open access) https://wesmckinney.com/book/
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.