Pandas GroupBy and Aggregation Explained: A Complete Guide (2026)
Pandas GroupBy and Aggregation is the tool that turns a long list of transactions into an actual answer: total sales by region, average score by team, count of orders by customer. Article 6 covered how a DataFrame's copy on write behavior keeps a selection independent from the original, and that same guarantee applies here too, since a groupby result is just another DataFrame. This guide covers the full split, apply, combine model, multiple aggregations with named aggregation, and the distinction that trips up almost everyone: .agg() versus .transform() versus .apply().
Quick Answer: Pandas GroupBy and Aggregation
Pandas GroupBy and Aggregation splits a DataFrame into groups based on shared column values, applies a function to each group, and combines the results into a new Series or DataFrame, the same split, apply, combine pattern SQL's GROUP BY clause uses. Use .agg() for a one row per group summary, .transform() when that summary needs to sit next to every original row, and named aggregation whenever a result needs several differently labeled columns at once.
The Slow Way, Then the Pandas Way
A small orders table needs one number per customer: total amount spent. Without groupby, that means an empty dictionary, a loop over every row, and adding to a running total by hand.
totals = {}
for _, row in orders.iterrows():
totals[row["customer"]] = totals.get(row["customer"], 0) + row["amount"]
Four lines become one with groupby:
import pandas as pd orders = pd.DataFrame({ "customer": ["Alex", "Alex", "Sam", "Sam", "Sam", "Sam"], "item": ["mug", "pen", "mug", "notebook", "pen", "mug"], "amount": [15.0, 5.0, 20.0, 10.0, 6.0, 8.0] }) orders.groupby("customer")["amount"].sum() # customer # Alex 20.0 # Sam 44.0 # Name: amount, dtype: float64
Same result, no manual bookkeeping, and unlike the loop above, it runs as a single vectorized pass instead of one Python level step per row. Article 11 covers exactly why that speed difference adds up on larger data.
Split, Apply, Combine: The Mental Model
Every groupby operation follows the same three step pattern, whether it appears in pandas or in SQL's own GROUP BY clause. Split divides the DataFrame into groups based on the values in one or more columns. Apply runs a function on each group independently. Combine stitches the per group results back into a single Series or DataFrame.
Calling .groupby() alone does not compute anything yet. It returns a GroupBy object, a lazy container that only runs the split once an actual aggregation method is called on it.
A groupby result is just another DataFrame under the hood, so Pandas 3.0's copy on write default applies here too. Anything returned by .agg() or .transform() behaves as an independent object, never a live view back into the original orders table.
Basic Aggregation
The built-in aggregation methods cover most everyday questions directly: .sum(), .mean(), .count(), .min(), .max(), .median(), and .nunique() for counting distinct values within each group.
orders.groupby("customer")["amount"].mean() # customer # Alex 10.0 # Sam 11.0 # Name: amount, dtype: float64 orders.groupby("customer")["item"].count() # how many orders per customer
Multiple Aggregations with .agg()
Passing a single function name works for one summary at a time. Real questions usually need several at once: total spent, average order size, and number of orders, all in one table.
orders.groupby("customer")["amount"].agg(["sum", "mean", "count"])
That works, but the result carries a MultiIndex on its columns (one level for the function name), and it scales awkwardly once different columns need different functions. A dictionary maps each column to its own aggregation instead:
orders.groupby("customer").agg({ "amount": "sum", "item": "count" })
Named aggregation, using keyword arguments inside .agg(), is the clearest choice once a result needs several differently labeled columns. Each keyword becomes the output column name directly, with no MultiIndex to flatten afterward:
orders.groupby("customer").agg( total_spent=("amount", "sum"), avg_order=("amount", "mean"), order_count=("amount", "count") ).reset_index() # customer total_spent avg_order order_count # 0 Alex 20.0 10.0 2 # 1 Sam 44.0 11.0 4
agg vs. transform vs. apply
These three methods answer different questions, and mixing them up is the single most common source of groupby confusion.
| Method | Output shape | Use it when |
|---|---|---|
| .agg() | One row per group | You want a summary |
| .transform() | Same shape as the original | The summary needs to sit next to every original row |
| .apply() | Depends on the function | Nothing else fits |
.transform() is the one most tutorials skip. It broadcasts a group level result back onto every original row instead of shrinking the table down:
orders["customer_avg"] = orders.groupby("customer")["amount"].transform("mean") # customer item amount customer_avg # 0 Alex mug 15.0 10.0 # 1 Alex pen 5.0 10.0 # 2 Sam mug 20.0 11.0 # 3 Sam notebook 10.0 11.0 # 4 Sam pen 6.0 11.0 # 5 Sam mug 8.0 11.0
Every row keeps its place, and each one gains its own customer's average alongside it, ready to compare a single order against what that customer typically spends. That is not something .agg() can do directly, since its entire purpose is to shrink the table down to one row per group.
Reach for .apply() only when neither of the other two fits. It is the most flexible option and also the slowest, since pandas cannot always run it as a single vectorized pass the way it can with the built-in aggregation strings.
Grouping by Multiple Columns
Passing a list of column names groups by every combination of values across them:
orders.groupby(["customer", "item"], as_index=False)["amount"].sum() # customer item amount # 0 Alex mug 15.0 # 1 Alex pen 5.0 # 2 Sam notebook 10.0 # 3 Sam mug 28.0 # 4 Sam pen 6.0
Sam's two separate mug purchases combine into one 28.0 row, the split, apply, combine pattern working exactly as described above. Adding as_index=False keeps customer and item as regular columns instead of folding them into the index, which is usually easier to work with right after.
Mistakes That Give Away a Beginner
- Being surprised by MultiIndex columns. A list of functions in
.agg(), like.agg(["sum", "mean"]), always produces a MultiIndex on the columns. - Reaching for .apply() out of habit when .agg() or .transform() would run faster and read more clearly.
- Expecting .transform() to shrink the table. It always matches the original row count, by design.
- Skipping .reset_index() after a groupby, then being unable to treat the group column as a normal column.
- Grouping by a column with missing values without checking it first. By default, pandas drops those rows from every group entirely.
Practice: Fix These Three Yourself
Three totals, one line
Using named aggregation, compute total_spent, avg_order, and order_count per customer in a single .agg() call.
Compare to the group
Add a column showing each row's amount as a percentage of its customer's total spend, using .transform().
Two levels deep
Group the orders table by both customer and item, and return the result with as_index=False so both stay as normal columns.
Frequently Asked Questions
What does groupby do in pandas?
It splits a DataFrame into groups based on shared values in one or more columns, applies a function to each group separately, and combines the results back into a single Series or DataFrame. Nothing is computed until an aggregation method actually runs.
What's the difference between agg, transform, and apply?
agg reduces each group to a summary, producing one row per group. transform keeps the original shape and broadcasts a result back onto every row. apply is the general purpose fallback for anything the other two can't express, at the cost of speed.
How do you rename columns after a groupby aggregation?
Use named aggregation. Pass keyword arguments to .agg() where each keyword becomes the output column name, such as total=("amount", "sum").
Can you group by multiple columns at once?
Yes. Pass a list of column names to groupby(), such as groupby(["customer", "item"]). The result groups by every combination of values across those columns.
Why does my aggregated DataFrame have two level column names?
Passing a list of functions to .agg(), like .agg(["sum", "mean"]), creates a MultiIndex on the columns: one level for the original column and one for each function. Named aggregation avoids this entirely.
Is pandas groupby the same as SQL GROUP BY?
They solve the same problem. Both split rows into groups and summarize each one, and pandas groupby was directly modeled on the SQL clause. Pandas adds transform and apply, which SQL has no direct equivalent for.
Conclusion: One Pattern, Three Tools
Split, apply, combine is the whole idea behind groupby, and everything else in this article is really just a variation on that same pattern. Reach for .agg() when the goal is a summary, .transform() when that summary needs to sit next to the original rows, and .apply() only when neither one fits.
Practice the three exercises above, then move to the next article in this cluster, which covers merging and joining: combining separate DataFrames the way a SQL join combines separate tables.
Next Up: Merging and Joining Pandas DataFrames
Inner, left, right, and outer joins, and how to combine tables that share a key column.
▶ Read the Merging GuideKhalid Hussain
Founder of Review Publically. MSc holder and Google Advanced Data Analytics certified. Teaches Python and SQL data analysis with a focus on current, correct, production-ready code rather than outdated conventions.
Related Articles