
Update, November 26, 2026: added a migration note on the pandas 3.0 categorical default, plus a diagram comparing the fixture’s row count with its known-amount count. The runnable example stays pinned to pandas 2.2.3.
“Count the sales by region” leaves two questions open: should count mean rows or nonmissing prices, and should an unknown region be dropped? With groupby, you can answer both explicitly.
Set the grain before grouping
This exercise runs on Python 3.11–3.13 with pandas 2.2.3; pick a compatible interpreter before you start, since this pinned version has no wheel for Python 3.14. Each row in the dataset below is one synthetic order, and keeping prices as integer cents avoids binary floating-point rounding when you sum them. The fixture intentionally includes one missing amount and one missing region.
Save the code as region_summary.py, install the pinned pandas version in your virtual environment, and run python region_summary.py.
import pandas as pd
orders = pd.DataFrame({
"region": ["north", "north", "south", None],
"cents": pd.array([1200, None, 800, 500], dtype="Int64"),
})
grouped = orders.groupby("region", dropna=False, sort=True)
summary = grouped.agg(
orders=("cents", "size"),
known_amounts=("cents", "count"),
)
summary["total_cents"] = grouped["cents"].sum(min_count=1)
assert summary["orders"].sum() == len(orders)
assert summary.loc["north", "orders"] == 2
assert summary.loc["north", "known_amounts"] == 1
assert summary.loc["north", "total_cents"] == 1200
print(summary.to_string())
Explain the numbers
Running the script prints a summary table with three group rows (north, south, and NaN for the missing region key):
Scroll sideways if the columns extend beyond the frame.
region (index) |
orders (size) |
known_amounts (count) |
total_cents (sum(min_count=1)) |
What this row means |
|---|---|---|---|---|
north |
2 |
1 |
1200 |
Two orders arrived; one had no recorded price, so the total covers only the one priced order |
south |
1 |
1 |
800 |
One complete order worth 800 cents |
NaN |
1 |
1 |
500 |
One priced order worth 500 cents had no region assigned and is kept visible by dropna=False |
North has two orders, one known amount, and a known-amount sum of 1200 cents. South has one order totaling 800 cents, and the unknown-region group has one order totaling 500 cents. Each region gets one row in the output, rather than each order.
size tallies every record in a group whatever its null fields, whereas count skips missing entries (NA / NaN / None) in the target column. Showing both exposes the incomplete north total, because any group where orders > known_amounts holds at least one unpriced order. A bare sum would mislead readers into believing both north orders were priced when one amount was missing.
min_count=1 makes an all-missing group’s sum stay <NA> instead of 0. By default in pandas, SeriesGroupBy.sum() uses min_count=0, which returns 0 when every value in a group is missing. In financial or operational reporting, 0 and <NA> are different statements: a total of 0 says amounts were recorded and summed to zero, whereas <NA> says no usable amount was available for that group.
Keep unknown groups on purpose
Here the code passes dropna=False. DataFrame.groupby() defaults to dropna=True, which quietly throws away any row with a null grouping key before aggregation starts. Under that default, the 500-cent order with region=None disappears from the summary and summary["orders"].sum() falls from 4 to 3. The assertion that compares grouped order counts with len(orders) flags the gap right away.
Still, final presentation tables do not have to display NaN as an index label. Missing regions can be filtered out upstream—following the cleaning guide—or mapped to a clear string category via orders["region"].fillna("unknown") prior to aggregation. Downstream code may expect region as an ordinary column instead of the DataFrame index. In that case, pass as_index=False to groupby(), or call .reset_index() on the aggregated result. The pandas 3.0 release notes record a change in the categorical observed default from False to True. This exercise stays on 2.2.3 and uses a noncategorical region column, so that change does not alter this fixture. When you group on a Categorical column, set observed=True or observed=False explicitly: observed=False keeps unused category levels with zero counts, while observed=True lists only the categories that appear in the data.
Add a new question without corrupting the old one
Divide summary["orders"] by summary["orders"].sum() to get each region’s share of total orders. Dividing by summary["known_amounts"].sum() is wrong unless your metric deliberately limits the denominator to priced orders. Pandas runs both formulas without complaint, but only one matches what the column label claims.
A mean amount (grouped["cents"].mean()) should be labeled clearly as an average over known_amounts only. If you fill missing amounts with 0 first, an unpriced order is treated as a free one, and north’s average drops from 1200.0 to 600.0. Do not fill missing values with zeros just to make an aggregate easier to compute.
Try adding a "west" region with two orders whose cents values are both None. With min_count=1, "west" will report orders=2, known_amounts=0, and total_cents=<NA>. Add a second order to "south" and predict the output before running the script. Those variations test the meaning of the report rather than its formatting.
Read SQL GROUP BY to see how databases apply these same rules. And before joining customer attributes onto orders, run merge cardinality checks so duplicate keys never multiply rows.
Source: pandas GroupBy guide, covering split-apply-combine, dropna, as_index, and missing grouping keys.
Download the complete example. Save the file before running it; the guide above names the required runtime.
Keep building
- Pandas data cleaning with an audit trail
Normalize a deliberately messy order file while separating rejected records from accepted observations.
- Pandas merge: prevent accidental row multiplication
Join orders to customers with explicit keys, cardinality validation, and a report of unmatched records.
- Read CSV in Python without guessing the data types
Parse a small order export, validate each record, and calculate totals without floating-point money errors.