sort_values
df.sort_values("col") returns the DataFrame sorted ascending by that column; add ascending=False for descending. Pass a list of columns, and a matching list of booleans, to sort by several columns in different directions.
Syntax
df.sort_values(by, ascending=True, na_position="last", key=None, inplace=False, ignore_index=False)| Part | What it is |
|---|---|
by | Column name or list of column names |
ascending | True, False, or a list matching by |
na_position | "last" (default) or "first" for where NaN goes |
key | Function applied to the sort column before sorting, e.g. str.lower |
ignore_index | If True, the result gets a fresh 0..n-1 index |
Examples
import pandas as pd
df = pd.DataFrame({"name": ["Ana", "Ben", "Cara", "Dan"],
"dept": ["Sales", "IT", "Sales", "HR"],
"salary": [50000, 62000, 58000, 45000]})
df.sort_values("salary", ascending=False)Result: name dept salary 1 Ben IT 62000 2 Cara Sales 58000 0 Ana Sales 50000 3 Dan HR 45000
df.sort_values(["dept", "salary"], ascending=[True, False])Result: name dept salary 3 Dan HR 45000 1 Ben IT 62000 2 Cara Sales 58000 0 Ana Sales 50000
Departments ascending, and inside each department the highest salary first.
df.sort_values("name", key=lambda s: s.str.lower(), ignore_index=True)Case-insensitive sort; ignore_index renumbers the rows 0 to 3.
Common mistakes
- The DataFrame looks unsorted after calling sort_values: it returns a new object, so write df = df.sort_values(...) or use inplace=True.
- Sorting a numeric column that is stored as text gives 10 before 2: convert with pd.to_numeric first.
- Uppercase names sort before lowercase ones because ASCII order; use key=lambda s: s.str.lower().
Practice sort_values
These drills check your answer on live data, free, no account needed.
- Sort by two columnsSort `emp` by department A to Z, and within each department by salary from highest to lowest. Keep the original row labels.
- Top three earnersReturn the three highest-paid employees with only the `name` and `salary` columns, highest salary first.
Questions
How do I get the top N rows by a column?
df.nlargest(3, "salary") or df.sort_values("salary", ascending=False).head(3). nsmallest does the opposite.
How do I sort descending by multiple columns?
Pass ascending=False once to apply it to all columns, or a list such as ascending=[False, True] to control each column.
Related
- rankHow to rank in pandas with rank: ascending or descending, tie methods (average, min, dense, first), ranking within groups, percentile ranks, integer output.
- head, tail and sampleHow to look at a pandas DataFrame with head, tail and sample: the first or last N rows, random rows with a seed, a fraction of rows, and showing all rows.
- idxmax and idxminHow to find which row holds the maximum or minimum in pandas with idxmax and idxmin, pull the full row with loc, get the max per group, and idxmax vs argmax.
- set_index and reset_indexHow to use set_index and reset_index in pandas: make a column the row index, go back to a plain column, drop the index, and flatten a groupby result.