Sub topic 7
Finding the top and bottom rows
This chapter covers nlargest and nsmallest, which pull the rows with the highest or lowest values out of a DataFrame or Series. It assumes you can already build a DataFrame, select columns, and tell a Series from a DataFrame. It also assumes you have met sort_values in the earlier chapters.
Why not just sort and slice?
To find the three best-selling rows, you can sort and take the first three:
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
print(df.sort_values("units", ascending=False).head(3))This works, but it sorts every row only to keep a few. nlargest and nsmallest say what you mean directly, and they use a selection algorithm that avoids a full sort on large tables.
print(df.nlargest(3, "units"))
print(df.nsmallest(2, "units"))nlargest(3, "units") returns these rows, largest first:
| index | region | units |
|---|---|---|
| 4 | South | 12.0 |
| 0 | North | 10.0 |
| 3 | East | 8.0 |
nsmallest(2, "units") returns rows 1 (5.0) and 5 (7.0), smallest first.
Three properties hold for both methods:
- The original index labels are kept, so you can still trace each row back to the source data.
- The result is already ordered.
nlargestgoes from high to low andnsmallestgoes from low to high. - The first argument
nhas no default in a DataFrame call. Ifnis larger than the number of rows, you get every row that qualifies.
Missing values are dropped
Row 2 has units of NaN. It does not appear in either result above, and that is deliberate. A missing value is neither large nor small, so both methods skip it.
This differs from sort_values, which keeps missing values and puts them last by default. The two approaches agree here because n is small. They differ when n reaches the number of non-missing values:
print(len(df.sort_values("units", ascending=False).head(6))) # 6, includes the NaN row
print(len(df.nlargest(6, "units"))) # 5, the NaN row is droppedThe nlargest call returns 5 rows because only five rows have a value in units.
Using them on a Series
On a single column, both methods return a Series with the original index:
print(df["units"].nlargest(3))4 12.0
0 10.0
3 8.0
Name: units, dtype: float64Use the Series form when you only need the values. Use the DataFrame form when you need the other columns of the same rows. The Series form has no column argument, because the Series is the column.
Handling ties with keep
When several rows tie at the cutoff, n cannot always be met cleanly. The price column shows this: three rows cost 4.0, and we ask for only two.
print(df.nlargest(2, "price")) # keep="first" is the default
print(df.nlargest(2, "price", keep="last"))
print(df.nlargest(2, "price", keep="all"))| keep | Rows returned | Behaviour |
|---|---|---|
| `"first"` | 1 and 2 | Keeps the earliest tied rows in the original order |
| `"last"` | 5 and 2 | Keeps the latest tied rows |
| `"all"` | 1, 2 and 5 | Keeps every tied row, so the result can exceed `n` |
Pick "first" or "last" when you need exactly n rows, for example to fill a fixed-size report. Pick "all" when dropping a tied row would be unfair, such as "everyone with a top-two score".
Several columns
Pass a list of columns to break ties with a second column. The columns are applied in order, like a multi-column sort where every column runs in the same direction:
clean = df.dropna(subset=["units"])
print(clean.nlargest(3, ["price", "units"]))Rows are ranked by price first, and units decides among equal prices. The result is rows 5 (price 4.0, units 7), 1 (price 4.0, units 5) and 4 (price 2.5, units 12).
There are two limits to know about:
- The columns must have a numeric or datetime type.
df.nlargest(3, ["region", "units"])raises aTypeErrorbecauseregionholds strings. To rank by text, usesort_valuesinstead. - All columns share one direction. If you need price high-to-low but units low-to-high, use
sort_valueswith a list forascending, as in the multi-column chapter.
I dropped the missing row in this example on purpose. Missing values in a secondary column make the outcome harder to predict, so clean them before a multi-column call.
The top rows within each group
nlargest looks at the whole table. A common follow-up is "the best row for each region". Sort once, then take the first row of each group with groupby(...).head:
best_per_region = (
df.sort_values("units", ascending=False)
.groupby("region")
.head(1)
)
print(best_per_region)This returns rows 4 (South, 12), 0 (North, 10) and 3 (East, 8). Replace 1 with a larger number to keep the top few rows per region. head takes the first rows of each group in the current row order, which is why the sort comes first.
You can also call nlargest on a grouped column:
print(df.groupby("region")["units"].nlargest(1))This gives the same values, but the result has a two-level index of region and original row label. That form suits a Series of values. The sort_values plus head form keeps whole rows in a flat table.
Choosing a method
Common errors
- Expecting NaN rows in the result. Both methods drop them. If you need missing rows to appear, use
sort_valueswithna_position. - Passing a string column.
nlargeston an object column raises aTypeError. Convert the column to a numeric type first, or sort instead. - Forgetting
n. On a DataFrame,df.nlargest("units")fails because the first argument isn. Writedf.nlargest(3, "units"). - Assuming exactly n rows.
keep="all"can return more, and missing values can make the result smaller. - Resetting the index by accident. These methods keep the original labels. If you want a fresh 0-based index, chain
.reset_index(drop=True).
Exercises
Exercise
Using the sales DataFrame above, which call returns the two rows with the smallest units, and which row label is missing from the result even though its units value is missing rather than large?
Show answer
df.nsmallest(2, "units") returns rows 1 (5.0) and 5 (7.0). Row 2, whose units is NaN, never appears, because nsmallest and nlargest skip missing values.
Exercise
You run df.nlargest(2, "price", keep="all") on the sales DataFrame and receive three rows instead of two. Why, and which keep setting would guarantee exactly two rows?
Show answer
Three rows share the highest price of 4.0 (rows 1, 2 and 5). keep="all" retains every row tied at the cutoff, so the result exceeds n. Using keep="first" (the default) or keep="last" returns exactly two rows.