Sorting and ranking
Last updated
Which day was busiest? Which store comes last? Most of those questions are answered by putting rows in order. In this lesson you'll sort by one column and by several, pick the top and bottom rows, rank values, and see what goes wrong when the numbers you're sorting are really text.
By the end of this lesson you can
- Sort a table by one or more columns, either way round
- Pick the biggest or smallest rows with
nlargestandnsmallest - Rank values, and put rows back with
sort_index - Spot numbers stored as text by how they sort, and fix them
Putting rows in order
Step through it, watching the index labels travel with their rows.
Now run the cells.
sort_values("kilos")sorts smallest first.ascending=Falsesorts biggest first.- Several columns: give a list. Here, store A to Z, then kilos biggest first within each store, so
ascendinggets a list too. nlargest(3, "kilos")is a shortcut for "sort biggest first and take three".nsmallestdoes the other end.rankgives each row its place: Batangas's 42 kg is rank 1. If two values tie, they share the rank between them (two tied for 2nd both get 2.5), which is why the ranks are floats.sort_index()puts the rows back in label order. The labels never changed, so the original order can always be found.
Sorting gives a new table and leaves sales as it was, so to keep the order, assign it: sales = sales.sort_values("kilos").
One detail for later: when rows tie, the default sort doesn't promise to keep them in their original order. If that matters (say, you sort by date, then by store, and want each store's days to stay in date order), add kind="stable".
Wrong way: prices sorted as text
A price list arrives with prices written as text, peso sign and comma included. Sort it.
₱1,200 comes first, then ₱300, ₱45 and ₱85. The column's dtype is str, so pandas sorts the prices as text, the way a dictionary sorts words: character by character. After the ₱, "1" comes before "3", which comes before "4" and "8", so ₱1,200 is "smallest". It doesn't know these are amounts.
The second cell fixes the column: remove the ₱ and the comma with str.replace, then make it numbers with astype("int64"). Now it sorts by amount, ₱45 first. (.str gives a Series the string methods you know from Python; lesson 4.8 has more of them.)
The sign to look for: a numeric column whose dtype is str, or a "smallest" value that obviously isn't. Check dtypes before you sort, and before you add up, too: you can't total ₱ text.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- pandas: pandas.DataFrame.sort_values: by, ascending, and kind="stable"
- pandas: pandas.DataFrame.nlargest: the top rows by a column
- pandas: pandas.Series.rank: ranks, and how ties are shared
- pandas: Working with text data: str.replace, for cleaning numbers stored as text