Data analysis · Intermediate · 16 min
Group and aggregate data in pandas
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pandas 3.1.1 · uv 0.13 (checked on python:3.15-slim)
You will summarise a shop's sales by region, month and city with pandas groupby, named aggregation, transform and filter, and finish with a regional report whose totals you have checked against the raw data.
On this page
Most questions you ask of a table are group questions: revenue per region, units per city per month, which cities carry the most weight. pandas answers all of them with one pattern, often called split, apply, combine. groupby splits the rows into groups by one or more key columns, a function runs on each group, and pandas combines the answers into a new table.
The pattern is short to write and quietly wrong more often than you would expect. Rows with a blank key vanish from every group, a sum skips missing values without telling you, and "count" means two different things. In this tutorial you build a small sales table for a shop with branches across Africa, summarise it four ways, and finish with a regional report whose totals you have checked against the raw rows.
If you think in SQL, groupby is GROUP BY and filter plays the part of HAVING; summarise data with GROUP BY and HAVING covers the SQL side, so this page stays with pandas.
Step 1 · Set up the project and the sales table
Make a throwaway folder, start a uv project in it and add pandas 3.1.1, pinned so the output below matches yours:
mkdir -p ~/groupby-demo
cd ~/groupby-demo
uv init --no-package --python 3.15
uv add "pandas==3.1.1"Now write the data. Each row is one product's sales in one city for one month. Three rows are deliberately awkward: two have no revenue recorded (Nairobi oil in September, Accra rice in October), and one, a new branch in Kano, has not been given a region yet.
cd ~/groupby-demo
cat > sales.csv <<'CSV'
month,region,city,product,units,revenue
2026-09,West,Lagos,Rice,40,500.00
2026-09,West,Lagos,Oil,30,180.00
2026-09,West,Accra,Rice,25,312.50
2026-09,East,Nairobi,Rice,20,250.00
2026-09,East,Nairobi,Oil,15,
2026-09,East,Kampala,Oil,10,60.00
2026-09,Southern,Johannesburg,Rice,35,437.50
2026-10,West,Lagos,Rice,45,562.50
2026-10,West,Accra,Oil,20,120.00
2026-10,West,Accra,Rice,30,
2026-10,East,Nairobi,Rice,25,312.50
2026-10,East,Kampala,Rice,10,125.00
2026-10,Southern,Johannesburg,Oil,25,150.00
2026-10,Southern,Johannesburg,Rice,30,375.00
2026-10,,Kano,Rice,12,150.00
CSV
wc -l sales.csvCheck it worked
wc -l reports 16 lines: a header and 15 rows. ls shows sales.csv next to pyproject.toml, uv.lock and main.py from uv init.
Step 2 · Group by one key, then by two
Start with the most common question, total revenue per region, then split it further by month. Select the column you want to aggregate after groupby, so pandas does not try to sum the city names too:
cd ~/groupby-demo
cat > keys.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
by_region = sales.groupby("region")["revenue"].sum()
print(by_region)
print()
by_region_month = sales.groupby(["region", "month"], as_index=False)["revenue"].sum()
print(by_region_month.to_string(index=False))
print()
print("groups:", len(by_region_month))
PY
uv run keys.pyWith one key the result is a Series indexed by region, sorted alphabetically. With a list of keys you get one row per combination that exists in the data. as_index=False keeps the keys as ordinary columns instead of a two-level index, which is usually what you want for a table you will save, chart or join to something else.
Group keys must match exactly. West and west, or West Africa and Afrique de l'Ouest from a French-language branch export, become separate groups. Map labels to one spelling before you group, the same way you clean join keys.
Check it worked
The first table shows East 747.5, Southern 962.5 and West 1675.0. The second has six rows, one per region and month, with West at 992.5 in September and Southern at 525.0 in October, and the script ends with groups: 6. Kano does not appear anywhere; you will come back to that.
Step 3 · Name your aggregations and mix functions per column
Real summaries need several numbers per group, from different columns. Named aggregation lets you write each output column as name=(input column, function):
cd ~/groupby-demo
cat > summary.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
summary = sales.groupby("region").agg(
rows=("units", "size"),
cities=("city", "nunique"),
units=("units", "sum"),
revenue=("revenue", "sum"),
biggest_sale=("revenue", "max"),
)
print(summary)
print()
mixed = sales.groupby("region").agg({"units": "sum", "revenue": ["sum", "max"]})
print(mixed)
print()
print("columns:", list(mixed.columns))
PY
uv run summary.pyThe first table has exactly the column names you chose, in your order. The second form, a dictionary of column to function or list of functions, is quicker to type but gives two-level column names such as ('revenue', 'max'). Those are awkward to select and turn into ugly headers in a CSV, so prefer named aggregation for anything you keep.
Check it worked
The named summary shows East with 5 rows, 2 cities, 80 units, 747.5 revenue and a biggest sale of 312.5; Southern with 3, 1, 90, 962.5 and 437.5; West with 6, 2, 190, 1675.0 and 562.5. The last line lists the dictionary version's columns as tuples.
Step 4 · Add each group's total back to every row with transform
agg shrinks each group to one row. Sometimes you want the opposite: keep every row and attach a group figure to it, such as each sale's share of its region's revenue. That is what transform does. It returns a result with the same length and row order as the original, so you can assign it straight to a new column:
cd ~/groupby-demo
cat > share.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
rows_before = len(sales)
sales["region_revenue"] = sales.groupby("region")["revenue"].transform("sum")
sales["share_of_region"] = sales["revenue"] / sales["region_revenue"]
cols = ["region", "city", "product", "revenue", "region_revenue", "share_of_region"]
print(sales[cols].round(3).to_string(index=False))
print()
print("rows before:", rows_before, "rows after:", len(sales))
print(sales.groupby("region")["share_of_region"].sum().round(6))
PY
uv run share.pyThe last check is worth keeping as a habit: shares within each group should add up to 1. If they do not, a row has slipped into the wrong group or the divisor is not the total you think it is.
Notice the Kano row. Its region is blank, so it belongs to no group, and its region_revenue is empty. The two rows with no revenue also get an empty share.
Check it worked
The table still has 15 rows, and the script prints rows before: 15 rows after: 15. Johannesburg's September rice is 0.455 of Southern's 962.5, October's Lagos rice is 0.336 of West's 1675.0, and Kano shows NaN in both new columns. Each region's shares add up to 1.0.
Step 5 · Keep only the groups that meet a rule
filter keeps or drops whole groups. You give it a function that receives one group as a DataFrame and returns True or False, and you get back the original rows of the groups that passed. Compare it with an ordinary row filter, which tests rows one at a time:
cd ~/groupby-demo
cat > keep.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
big_rows = sales[sales["revenue"] >= 300]
print("cities with a sale of 300 or more:", sorted(big_rows["city"].unique()))
big_cities = sales.groupby("city").filter(lambda g: g["revenue"].sum() >= 500)
print("rows kept:", len(big_cities))
print("cities kept:", sorted(big_cities["city"].unique()))
PY
uv run keep.pyThe two answer different questions. Accra has one large sale, so it passes the row test, but its total over both months is 432.50, so it fails the group test. Use filter when the rule is about the group as a whole: cities with at least 500 in revenue, products sold in every month, customers with three or more orders.
Check it worked
The row filter finds Accra, Johannesburg, Lagos and Nairobi. The group filter keeps 9 rows from three cities: Johannesburg, Lagos and Nairobi. Accra and Kampala are gone.
Step 6 · Count rows with size, values with count, and find the missing group
Three things in this data slip past a quick look: two blank revenues and a blank region. Put the checks side by side. size counts rows in a group; count counts the values that are not missing; dropna=False keeps a group for the blank key instead of dropping it:
cd ~/groupby-demo
cat > missing.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
g = sales.groupby("region", dropna=False)
checks = pd.DataFrame({
"rows": g.size(),
"revenue_values": g["revenue"].count(),
"revenue": g["revenue"].sum(),
"mean_revenue": g["revenue"].mean().round(2),
})
checks["missing"] = checks["rows"] - checks["revenue_values"]
print(checks)
print()
print("sum of default groups:", sales.groupby("region")["revenue"].sum().sum())
print("sum with dropna=False:", g["revenue"].sum().sum())
print("grand total:", sales["revenue"].sum())
PY
uv run missing.pyRead the table as a list of warnings:
- East has 5 rows but only 4 revenue values. Its sum, 747.5, treats the missing Nairobi row as zero, and its mean, 186.88, is the average of the 4 known values, not of 5. Neither is wrong, but a report should say one sale is unpriced. If a group could have no values at all,
sum(min_count=1)returnsNaNfor it instead of a reassuring 0. - The
NaNrow is Kano. By defaultgroupbydrops rows whose key is missing, so every regional total before this step left out 150.00. - The default groups add up to 3385.0 while the raw column adds up to 3535.0. Comparing the sum of your groups with the grand total is the fastest check you have.
Missing values are common in branch exports that come in from patchy connections or are typed up later from paper. The rows against revenue_values comparison tells you how much of a total rests on incomplete data.
Check it worked
The table shows East with 5 rows, 4 revenue values and 1 missing; West with 6, 5 and 1; and a NaN region with 1 row and 150.0 revenue. The last three lines show 3385.0 for the default groups and 3535.0 both with dropna=False and for the grand total.
Step 7 · Group a categorical column with observed=
When a key has a fixed list of possible values, such as regions you report on every month whether or not they sold anything, store it as a categorical. You get a set order and can ask for empty groups. Here North is a region with no sales yet:
cd ~/groupby-demo
cat > cats.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
sales["region"] = pd.Categorical(
sales["region"], categories=["North", "West", "East", "Southern"]
)
print(sales.groupby("region")["revenue"].sum())
print()
print(sales.groupby("region", observed=False)["revenue"].sum())
print()
seen = sales.groupby(["region", "month"])["revenue"].sum()
grid = sales.groupby(["region", "month"], observed=False)["revenue"].sum()
print("region-month groups, observed:", len(seen))
print("region-month groups, all categories:", len(grid))
PY
uv run cats.pySince pandas 3.0, observed=True is the default: only categories that appear in the data become groups. observed=False adds the empty ones, with a sum of 0.0. With several categorical keys it builds every combination, so 4 regions by 2 months gives 8 groups even though only 6 have data. That is useful for a fixed report layout, and a trap with many keys, where the grid can grow far larger than the data. The groups also follow the category order (West, East, Southern) rather than the alphabet.
Check it worked
The first result lists West 1675.0, East 747.5 and Southern 962.5, in that order, with no North. The second starts with North 0.0. The last two lines report 6 observed region-month groups and 8 with all categories.
Step 8 · Build a regional report you can trust
Put it together. Give the blank region a visible label so it cannot fall out, summarise with named aggregation, check the groups add up to the raw data, and save the result:
cd ~/groupby-demo
cat > report.py <<'PY'
import pandas as pd
sales = pd.read_csv("sales.csv")
sales["region"] = sales["region"].fillna("Unassigned")
report = (
sales.groupby("region")
.agg(
rows=("units", "size"),
missing_revenue=("revenue", lambda s: s.isna().sum()),
units=("units", "sum"),
revenue=("revenue", "sum"),
)
.sort_values("revenue", ascending=False)
)
assert report["revenue"].sum() == sales["revenue"].sum(), "groups do not add up"
assert report["rows"].sum() == len(sales), "rows went missing"
report["share"] = (report["revenue"] / report["revenue"].sum()).round(3)
report.to_csv("region_report.csv")
print(report)
PY
uv run report.py
cat region_report.csvThe two assert lines are the point of this step. If someone later adds a filter, changes a key or reads a file with a new blank column, the script stops instead of printing a believable, smaller total. The missing_revenue column carries the warning from the previous step into the report itself, so whoever reads it knows West and East each have one unpriced sale.
Check it worked
The script prints four regions sorted by revenue: West 1675.0 (share 0.474), Southern 962.5, East 747.5 and Unassigned 150.0 (0.042). region_report.csv has a header and those four rows. When you have finished, delete the folder with rm -r ~/groupby-demo.
Next steps
- Turn the region by month results into a wide table and back again: reshape data with pivot and melt.
- Join sales to customers and products before you group them, without losing rows: join DataFrames in pandas without losing or duplicating rows.
- Write the same summaries in SQL: summarise data with GROUP BY and HAVING.
- If you are coming from SUMIFS and pivot tables, move from spreadsheet formulas to pandas maps each one to its pandas form.
Part of these paths
Related tutorials
- Join DataFrames in pandas without losing or duplicating rowsYou will join orders to customers and products with pandas merge, compare the four join types by row count, catch duplicate and mismatched keys with validate= and indicator=, list unmatched rows with an anti-join and stack new batches with concat.
- Reshape data between wide and long with pivot and meltYou will turn a one-column-per-month spreadsheet export into long, tidy rows with pandas 3.1 and back again, handle duplicate entries with pivot_table, compute shares with crosstab and move between shapes with stack and unstack.
- Summarise data in SQL with GROUP BY, HAVING and aggregatesYou will turn twelve order rows into a PostgreSQL 18 revenue report by month and region, with subtotals, saved as a view and a CSV file that matches a hand check.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials