Sub topic 13
Sorting a grouped summary
This chapter assumes you can build a DataFrame, select columns, and run groupby with named aggregation. It also assumes you know sort_values from earlier chapters. Here you combine them: aggregate first, then sort the summary.
Why sort after aggregating
groupby returns its result ordered by the group keys, alphabetically by default. That order is rarely the one a reader wants. Usually you want the biggest groups first.
The summary is an ordinary DataFrame whose index holds the group keys. Its columns are the names you chose in named aggregation. Because of that, sort_values works on it like on any other DataFrame.
Sort by an aggregated column
Sort by the name you gave in agg, not by the original column name.
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],
})
summary = df.groupby("region").agg(
total_units=("units", "sum"),
avg_price=("price", "mean"),
orders=("product", "size"),
)
print(summary.sort_values("total_units", ascending=False)) total_units avg_price orders
region
South 17.0 3.25 2
East 15.0 3.25 2
North 10.0 3.25 2North has three rows, but one units value is missing. sum skips it, so North totals 10.0 while orders still counts 2 rows per region.
Break ties with a second column
All three regions share the same avg_price. Sorting on that column alone would leave their order to the sort algorithm, which is hard to predict. Pass a list so a second column decides ties.
print(summary.sort_values(["avg_price", "total_units"], ascending=[False, False]))Each region has avg_price 3.25, so the result is ordered by total_units: South, East, North.
Keep the keys as a column
By default the group keys become the index. With as_index=False they stay a normal column. Adding ignore_index=True then gives a clean row count from 0.
flat = df.groupby("region", as_index=False).agg(
total_units=("units", "sum"),
orders=("product", "size"),
)
print(flat.sort_values("total_units", ascending=False, ignore_index=True)) region total_units orders
0 South 17.0 2
1 East 15.0 2
2 North 10.0 2Take the top groups
Chain head after sorting to keep only the leaders. nlargest does both steps in one call.
print(summary.sort_values("total_units", ascending=False).head(2))
print(summary.nlargest(2, "total_units"))Both lines print South and East.
Exercise
Using the df above, build a summary of average units per product named avg_units. Sort it so the product with the highest average comes first. Which product is first, and what is its average?
Show answer
Use df.groupby("product").agg(avg_units=("units", "mean")).sort_values("avg_units", ascending=False). Product A is first with an average of 10.0, from the values 10, 8 and 12. Product B averages 6.0 because the missing value is skipped, leaving 5 and 7.