Sub topic 7
Finding the top and bottom rows
This chapter assumes you can build a DataFrame, select columns, and use sort_values. It uses the same small sales table as the earlier chapters.
Why not just sort and slice?
To get the three best-selling rows, you could write df.sort_values("units", ascending=False).head(3). That works. pandas also has nlargest and nsmallest, which say what you mean in one call and avoid fully sorting a large table when n is small.
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.nlargest(3, "units"))
print(df.nsmallest(2, "units"))The first call returns rows 4, 0 and 3, with 12, 10 and 8 units. The second returns rows 1 and 5, with 5 and 7 units. The rows keep their original index labels and are ordered from most extreme to least.
Row 2 has a missing units value. nlargest and nsmallest skip missing values, so that row can never appear in the result. This differs from sort_values, which keeps missing values and places them last by default.
Ties
Several rows can share the same value at the cutoff. The keep argument decides what happens.
print(df.nlargest(2, "price"))
print(df.nlargest(2, "price", keep="last"))
print(df.nlargest(2, "price", keep="all"))Three rows (1, 2 and 5) have the top price of 4.0. The values of keep behave as follows:
| `keep` | Behaviour |
|---|---|
| `"first"` (default) | Keeps the earliest tied rows in the table until `n` is reached. |
| `"last"` | Keeps the latest tied rows. |
| `"all"` | Keeps every tied row, so the result can have more than `n` rows. |
Use keep="all" when dropping a tied row would be unfair, such as a "top 2 products" report.
Several columns
Pass a list of column names to break ties with a second column. The columns are compared in order.
print(df.nlargest(3, ["price", "units"]))Rows are ordered by price first, then by units among equal prices.
Common errors
- Non-numeric columns.
df.nlargest(3, "region")raises aTypeErrorbecause the column holds strings. These methods work on numeric and datetime columns. For text, usesort_valuesandhead. - Forgetting the column on a DataFrame. On a DataFrame,
nlargestrequires thecolumnsargument. On a Series, you calldf["units"].nlargest(3)and it returns a Series. - Expecting
nrows. You get fewer thannif there are not enough non-missing values. Withkeep="all"you can get more.
Exercise
Using the table above, which call returns every row that ties for the highest price, even if that gives more than two rows: df.nlargest(2, "price") or df.nlargest(2, "price", keep="all")? How many rows does it return?
Show answer
df.nlargest(2, "price", keep="all"). Rows 1, 2 and 5 all have a price of 4.0, so it returns three rows. The default keep="first" returns only two.