Sub topic 13
Sorting a grouped summary
This chapter assumes you can build a DataFrame, select columns, and tell a Series from a DataFrame. It also assumes you have used groupby with named aggregation, which the previous chapter covered. Here you will put the grouped result into a useful order, deal with ties, and handle the cases where the grouped result is not a flat table.
What a grouped summary looks like
A groupby followed by agg returns a new DataFrame. Its index holds the group keys, and its columns hold the aggregated values. Two facts about that result drive everything below.
- The rows are already sorted, but by the group key, not by your numbers.
groupbyusessort=Trueby default, so the keys come out in ascending order. - The key is the index, not a column. You sort by the numbers with
sort_values, and by the keys withsort_index.
The examples use the sales table from earlier in the tutorial. Later blocks continue from the variables defined in the first one.
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)
print(summary.sort_values("total_units", ascending=False))The first print shows the summary in key order: East, North, South. The second shows it ordered by total units:
total_units avg_price orders
region
South 17.0 3.25 2
East 15.0 3.25 2
North 10.0 3.25 2sort_values returns a new DataFrame and leaves summary unchanged. Assign the result if you want to keep the order.
Sorting by the aggregated column
Name the column in sort_values, as you would for any DataFrame. Because named aggregation gave the columns readable names, the call reads like a sentence: sort by total_units, largest first.
You can also skip the intermediate DataFrame and chain the calls:
ranked = (
df.groupby("region")
.agg(total_units=("units", "sum"), orders=("product", "size"))
.sort_values("total_units", ascending=False)
)
print(ranked)Chaining keeps the whole recipe in one expression: group, aggregate, order. It also avoids a half-finished summary variable that you might sort twice by mistake.
Ties and stable ordering
In this data every region has the same avg_price of 3.25 and the same orders count of 2. Sorting by a column full of ties raises the question of which tied row comes first.
With a single column, sort_values defaults to kind="quicksort", which does not promise to keep tied rows in their original order. Pass kind="stable" when the order of ties matters:
print(summary.sort_values("avg_price", ascending=False, kind="stable"))Tied rows now keep their incoming order: East, North, South. A stable sort is also what lets you sort twice. Sort by the secondary key first, then by the primary key with kind="stable". For most work, a second sort column is clearer, as the next section shows.
Sorting by several summary columns
Pass a list of columns and a matching list of flags to order by one measure and break ties with another:
print(
summary.sort_values(
["orders", "total_units"],
ascending=[False, False],
)
)Here all regions have two orders, so total_units decides the order. The tie-breaking column is the one that does the work in this example.
sort_values also accepts the name of an index level. The group key region is an index level, so you can use it as a final tie-breaker without calling reset_index:
print(summary.sort_values(["avg_price", "region"], ascending=[False, True]))Every region ties on avg_price, so the output is alphabetical by region. This gives you a deterministic order for tied values.
Keeping the group order or sorting by key
Two related controls decide the order before you call sort_values.
groupby(..., sort=False)keeps the groups in order of first appearance. Forregionthat gives North, South, East. It can also be slightly faster on large data, because pandas skips sorting the keys.sort_index()on the result orders by the group keys. Usesort_index(ascending=False)for reverse alphabetical order, orsort_index(key=...)for a custom key function.
unsorted_groups = df.groupby("region", sort=False)["units"].sum()
print(unsorted_groups)
print(unsorted_groups.sort_index(ascending=False))The sort=False setting matters only for ordering. The numbers in each group are the same either way.
Adding derived columns before sorting
The best sort key is often not one of the aggregates. Compute it as a new column, then sort by it:
summary["share"] = summary["total_units"] / summary["total_units"].sum()
print(summary.sort_values("share", ascending=False))You can also run a cumulative total over the sorted result to find how many regions account for most of the volume:
ordered = summary.sort_values("total_units", ascending=False)
ordered["cum_share"] = ordered["total_units"].cumsum() / ordered["total_units"].sum()
print(ordered[["total_units", "cum_share"]])The order matters here. cumsum adds values in row order, so sorting first and then calling cumsum gives a running total from the biggest group down.
Sorting a Series with a MultiIndex
Grouping by two keys and selecting one column gives a Series with a two-level index. Sorting it with sort_values orders all rows together and ignores the hierarchy:
by_pair = df.groupby(["region", "product"])["units"].sum()
print(by_pair.sort_values(ascending=False))The result starts with South A at 12.0 and ends with North B at 0.0. That zero comes from the missing value: the sum of a group that has only missing entries is 0.
To keep the best row in each group, sort first and then take the head of each group:
top_per_region = (
by_pair.sort_values(ascending=False)
.groupby(level="region")
.head(1)
)
print(top_per_region)region product
South A 12.0
North A 10.0
East A 8.0
Name: units, dtype: float64head(1) returns rows in their current order, so the global sort carries through. This is usually simpler than sorting inside each group with apply.
To turn the result back into an ordinary table, call reset_index(). For a Series that gives a DataFrame with region, product and units columns. Add ignore_index=True to sort_values if the index is already a plain column and you want fresh row numbers.
flowchart LRThe pipeline at a glance
Missing values and sorted summaries
Missing values enter a grouped sort in three places.
- Missing values in the data. Most aggregations skip them. The North total above is 10.0 because the missing unit count was ignored.
meandivides by the number of present values, andsizecounts rows regardless. - Missing values in the result. An aggregate can come out missing, for example
meanon a group with no present values.sort_valuesplaces these last by default, whether the order is ascending or descending. Usena_position="first"to move them to the top. - Missing group keys.
groupbydrops rows whose key is missing, becausedropna=Trueis the default. Passdropna=Falseif you need a group for them. The resultingNaNkey then sorts last in the index.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `KeyError` when sorting by the group column | The key is the index, not a column | Use `sort_index`, include the level name in `sort_values`, or call `reset_index` first |
| Largest group appears last | `ascending=True` is the default | Pass `ascending=False` |
| Tied rows change order between runs or versions | Default sort is not stable | Use `kind="stable"` or add a tie-breaking column |
| Sorting the grouped Series ignores regions | A flat sort ignores the MultiIndex levels | Group again on `level=` and use `head` or `nlargest` |
| Row counts do not add up | Missing keys were dropped | Use `dropna=False` |
Exercise
Using the sales DataFrame from this chapter, write code that gives the product with the most total units inside each region. Which product is it for North, and why is the other North product not first?
Show answer
Run by_pair = df.groupby(["region", "product"])["units"].sum(), then by_pair.sort_values(ascending=False).groupby(level="region").head(1). For North the result is product A with 10.0 units. Product B has a total of 0.0, because its only unit count is missing and the sum skips it, so A sorts above it.
Exercise
A summary is sorted by avg_price descending, and every region has the same average price. How do you make the order reproducible?
Show answer
Either pass kind="stable" so tied rows keep their incoming order, or sort by a second column as a tie-breaker, for example summary.sort_values(["avg_price", "region"], ascending=[False, True]).