pandas nlargest and nsmallest
df.nlargest(3, "col") returns the 3 rows with the highest values in col, highest first, and nsmallest does the same for the lowest. It reads better than sort_values(...).head(3) and gives the same rows. When several rows tie for the last place, keep="all" returns all of them.
Syntax
df.nlargest(n, columns, keep="first") | df.nsmallest(n, columns, keep="first") | Series.nlargest(n)| Part | What it is |
|---|---|
n | How many rows to return |
columns | Column name, or a list to break ties with further columns |
keep | "first" (default) or "last" picks one of the tied rows; "all" keeps every tie, so more than n rows can come back |
Examples
import pandas as pd
df = pd.DataFrame({"rep": ["Ana", "Ben", "Cy", "Di", "Eli"],
"region": ["N", "N", "S", "S", "S"],
"sales": [300, 450, 450, 120, 380]})
df.nlargest(2, "sales")Result:
rep region sales
1 Ben N 450
2 Cy S 450df.nsmallest(1, "sales")Result:
rep region sales
3 Di S 120df["sales"].nlargest(2)Result:
1 450
2 450
Name: sales, dtype: int64On a Series there is no column to name.
df.sort_values("sales", ascending=False).groupby("region").head(1)Result:
rep region sales
1 Ben N 450
2 Cy S 450Top row in each region: sort first, then take the head of every group.
Try it yourself
Return the three highest-paid employees with only the name and salary columns, highest salary first.
emp: 8 rows, first 4 shown
| emp_id | name | dept | salary | city | years |
|---|---|---|---|---|---|
| 1 | "Ava Chen" | "Sales" | 62000 | "Boston" | 3 |
| 2 | "Ben Ortiz" | "Engineering" | 98000 | "Austin" | 6 |
| 3 | "Cara Patel" | "Marketing" | 71000 | "Boston" | 4 |
| 4 | "Dev Singh" | "Engineering" | 105000 | "Denver" | 9 |
Free, no account needed. Real pandas runs in your browser; the first run takes a few seconds to load Python.
Common mistakes
- TypeError on a text column: nlargest works on numbers and dates. For text use sort_values("col").head(n).
- Expecting exactly n rows with keep="all": ties at the cut-off are all returned, so the result can be longer than n.
- Using nlargest on the whole DataFrame after groupby: it is not a group method on a DataFrame. Sort and use groupby(...).head(n), or apply nlargest to one column.
More practice: nlargest and nsmallest
These drills check your answer on live data, free, no account needed.
- Top two orders per regionReturn the two highest-revenue orders in each region as a DataFrame with the columns `region`, `order_id` and `revenue`, sorted by region A to Z and within each region by revenue from highest to lowest. A region with a single order contributes just that order. Row labels do not matter.
Questions
Is nlargest faster than sorting?
For a small n on a large table, yes: it does not need to sort every row. For most everyday sizes the difference does not matter.
How do I get the row with the single highest value?
df.nlargest(1, "col"), or df.loc[df["col"].idxmax()] for that one row as a Series.
How do I get the top N per group?
df.sort_values("col", ascending=False).groupby("key").head(n).
Related
- sort_valuesHow to sort a pandas DataFrame with sort_values: ascending and descending, several columns with mixed order, NaN first, sort by index and reset the index.
- 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.
- rankHow to rank in pandas with rank: ascending or descending, tie methods (average, min, dense, first), ranking within groups, percentile ranks, integer output.
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.
Interview and translation guides
- Timed mock interview
- pandas interview questions
- The pandas interview round
- SQL to pandas
- XLOOKUP in pandas
- pandas for Excel users
- groupby exercises