Sorting Data
Python · Pandas Basics
Theory
df.sort_values('amount') returns the rows ordered by a column, smallest first; ascending=False reverses it. To sort by several keys pass lists: df.sort_values(['city', 'amount'], ascending=[True, False]) orders by city A-Z and, inside each city, by amount high to low - exactly SQL's ORDER BY city ASC, amount DESC. Missing values go last unless na_position='first'. The index labels travel with their rows, so add .reset_index(drop=True) if you want 0, 1, 2 again.
df.sort_index() sorts by the row labels instead (handy after a groupby or set_index), and sort_index(axis=1) sorts column names. For 'top n' questions, df.nlargest(3, 'amount') and df.nsmallest(3, 'amount') are shortcuts that are clearer, and on large data faster, than sorting everything and taking head(3).
Why we use it
Sorted output is easier to read and is required for many tasks: top-N lists, reports in a fixed order, running totals and lag comparisons that depend on row order.
When to use it
Use sort_values for ordering by data, sort_index for ordering by labels, and nlargest/nsmallest for a quick top or bottom n. Do not sort just to find a max - idxmax() or max() is enough.
How it works
- df.sort_values(['city', 'amount'], ascending=[True, False])
- Order rows by the first key, city A-Z
- Two rows have the same city? Yes: Break the tie with amount, high to low. No: Keep the city order.
- Place NaN rows according to na_position
- Sorted DataFrame (original index labels kept)
Syntax
df.sort_values(by, ascending=True, na_position='last')
df.sort_values(['a', 'b'], ascending=[True, False])
df.sort_index()
df.nlargest(n, 'col')Example
print(df.sort_values(['city', 'amount'], ascending=[True, False]))
print(df.nlargest(2, 'amount'))Key points
- Pass lists to by= and ascending= for multi-key sorts
- Rows keep their index labels; use reset_index(drop=True) for a clean index
- NaN goes last by default; change with na_position='first'
- nlargest / nsmallest are shortcuts for ORDER BY ... LIMIT n
- SQL equivalent: ORDER BY city ASC, amount DESC