Pandas GroupBy Aggregation: agg(), Named and Custom Functions

A regional sales manager sent me ten rows of store orders and asked one question: what did each region sell, on average and in total? A pandas groupby aggregation answers that in one line, as long as you call agg() on the grouped data.

The trouble starts when you need several numbers per group. Chained calls like .sum() then .mean() give you separate Series, and a plain dictionary gives you awkward two-level column names.

Quick answer: group with groupby(), then pass named tuples to agg() so every result column gets a clean name:

df.groupby("region").agg(total=("revenue", "sum"), avg_units=("units", "mean"))

In this tutorial, I’ll walk you through pandas groupby aggregation on one sales table: built-in methods, lists of functions, dictionaries, named aggregation, custom functions, multi-column groups, dates, missing values and the errors I see most.

How Does pandas GroupBy Aggregation Work?

groupby() splits the rows into groups by a key column. An aggregation then squeezes each group down to one value, and pandas combines those values into a new Series or DataFrame indexed by the key.

Here’s the running sample: ten electronics orders from four US regions in early 2026, tested with Python 3.12.5 and pandas 3.0.6. If you only want to split rows without reducing them, my guide to pandas groupby without aggregation covers that side.

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

The fastest aggregations are the built-in methods on the grouped column. Pick the column with brackets, then call the method:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

print(df.groupby("region")["revenue"].sum())
print(df.groupby("region")["units"].mean())

Output:

region
Midwest     1,199.85
Northeast   9,499.83
South       7,459.77
West        4,389.83
Name: revenue, dtype: float64
region
Midwest     15.00
Northeast    5.67
South        7.67
West         5.67
Name: units, dtype: float64

The Northeast leads with $9,499.83 in revenue, while the Midwest averages the most units per order at 15. Notice the result is sorted by region name, because groupby() sorts keys by default (sort=False turns that off).

Other built-ins work the same way: min(), max(), median(), std(), var(), count(), size(), nunique(), first() and last(). They run in optimized code, so they beat a Python function on big tables.

size() per group works like counting rows in a pandas DataFrame, just split by key.

Apply Several Functions to One Column with agg()

When the manager wants totals, averages and the biggest order side by side, pass a list of function names to agg() (its long name is aggregate()). Each name becomes one column:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

funcs = ["sum", "mean", "max", "count"]
summary = df.groupby("region")["revenue"].agg(funcs)
print(summary)

Output:

               sum     mean      max  count
region                                     
Midwest   1,199.85 1,199.85 1,199.85      1
Northeast 9,499.83 3,166.61 3,999.96      3
South     7,459.77 2,486.59 4,999.95      3
West      4,389.83 1,463.28 1,999.98      3
VS Code output of pandas groupby agg with a list of sum, mean, max and count on the revenue column per region
One agg() call returns four columns per region, and the South’s biggest single order is the Dallas laptop sale.

The count column is the number of non-missing values in each group. For distinct values or full frequency tables, see counting unique values in a pandas column.

Note: strings like "sum" map to pandas’ optimized methods, while a Python callable such as the built-in sum runs once per group. That’s why I stick with the string names.

Use a Dictionary to Aggregate Different Columns

A dictionary maps each column to its own function or list of functions. It’s handy when revenue needs a total but units need both a total and an average:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

out = df.groupby("region").agg({"revenue": "sum", "units": ["sum", "mean"]})
print(out.columns.tolist())

out.columns = ["_".join(col) for col in out.columns]
print(out)

Output:

[('revenue', 'sum'), ('units', 'sum'), ('units', 'mean')]
           revenue_sum  units_sum  units_mean
region                                       
Midwest       1,199.85         15       15.00
Northeast     9,499.83         17        5.67
South         7,459.77         23        7.67
West          4,389.83         17        5.67

Because units got two functions, pandas builds a two-level column index of (column, function) tuples. The list comprehension joins each pair with an underscore, so you get flat names like units_mean. My post on getting pandas column names shows more ways to inspect them.

This works, but you have to rename columns afterward. That extra step is why I moved to named aggregation for anything a teammate will read.

Named Aggregation: Clean Column Names in One Call

Named aggregation passes keyword arguments to agg(). Each keyword is the output column, and its value is a (column, function) tuple. It’s been available since pandas 0.25, so any current install has it.

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

report = df.groupby("region").agg(
    total_revenue=("revenue", "sum"),
    avg_units=("units", "mean"),
    orders=("product", "size"),
    products=("product", "nunique"),
    first_sale=("order_date", "min"),
)
print(report.sort_values("total_revenue", ascending=False))

Output:

           total_revenue  avg_units  orders  products first_sale
region                                                          
Northeast       9,499.83       5.67       3         2 2026-01-05
South           7,459.77       7.67       3         3 2026-01-20
West            4,389.83       5.67       3         3 2026-01-28
Midwest         1,199.85      15.00       1         1 2026-03-16
VS Code output of a pandas named aggregation report with total revenue, average units, orders, products and first sale per region
Every column has a readable name, regions are sorted by total revenue, and the Midwest’s single order shows one product.

Each column can use a different source column, which a list can’t do. I sorted the result with sort_values(); sorting a pandas DataFrame by column covers multi-key and descending sorts.

Pro Tip: pd.NamedAgg(column="revenue", aggfunc="sum") is the long form of the same tuple. It reads well in code reviews, but the plain tuple is shorter and does the same thing.

Write a Custom Aggregation Function for groupby

Any function that takes a Series and returns one value works here. spread() returns the gap between the largest and smallest order, and a lambda returns the 90th percentile. If lambdas are new to you, read how to use lambda functions in Python first.

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

def spread(s):
    return s.max() - s.min()

g = df.groupby("region")["revenue"]
print(g.agg(["sum", spread, lambda s: s.quantile(0.9)]))

Output:

               sum   spread  <lambda_0>
region                                 
Midwest   1,199.85     0.00    1,199.85
Northeast 9,499.83 1,500.06    3,799.96
South     7,459.77 4,040.07    4,299.95
West      4,389.83 1,360.06    1,949.97
VS Code output of pandas groupby agg with a custom spread function and a lambda, with the lambda column labeled lambda_0
The custom spread column keeps its function name, but pandas labels the lambda column <lambda_0>.

That <lambda_0> label tells a reader nothing. Named keywords also work directly on a grouped Series, so give every function, lambda included, a proper column name:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

def spread(s):
    return s.max() - s.min()

g = df.groupby("region")["revenue"]
print(g.agg(total="sum", spread=spread,
            p90=lambda s: s.quantile(0.9)))

Output:

             total   spread      p90
region                              
Midwest   1,199.85     0.00 1,199.85
Northeast 9,499.83 1,500.06 3,799.96
South     7,459.77 4,040.07 4,299.95
West      4,389.83 1,360.06 1,949.97

Same numbers, but now the 90th percentile column is called p90. I use this form whenever a lambda is involved.

Custom Python functions run once per group, so they’re slower than built-in strings. On a few thousand groups you won’t notice, but on millions of rows check for a built-in such as quantile or nunique first.

How Do You Aggregate Using Two Columns at Once?

agg() hands your function one column at a time, so it can’t see revenue and units together. For an average selling price per region, sum both columns first and divide the totals:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

g = df.groupby("region").agg(revenue=("revenue", "sum"),
                             units=("units", "sum"))
g["avg_price"] = g["revenue"] / g["units"]
print(g)

price = df.groupby("region").apply(
    lambda d: d["revenue"].sum() / d["units"].sum()
)
print(price.round(2))

Output:

           revenue  units  avg_price
region                              
Midwest   1,199.85     15      79.99
Northeast 9,499.83     17     558.81
South     7,459.77     23     324.34
West      4,389.83     17     258.23
region
Midwest      79.99
Northeast   558.81
South       324.34
West        258.23
dtype: float64

Both approaches return the same prices, such as $324.34 per unit in the South. The apply() version receives each group as a full DataFrame, which is flexible but much slower. My guide on applying a function to each row in pandas explains how apply() behaves.

Important: don’t average the per-order prices with mean(). A $79.99 headset line and a $999.99 laptop line would count equally, so the result wouldn’t match what the region actually earned per unit.

Group by Multiple Columns and Get a Flat Table

Pass a list of keys to group by region and store together. With as_index=False, the keys stay ordinary columns instead of a two-level row index:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

by_store = df.groupby(["region", "store"], as_index=False).agg(
    revenue=("revenue", "sum"),
    orders=("product", "size"),
)
print(by_store)

Output:

      region     store  revenue  orders
0    Midwest   Chicago 1,199.85       1
1  Northeast    Boston 3,999.96       1
2  Northeast  New York 5,499.87       2
3      South   Atlanta 1,499.94       1
4      South    Dallas 5,959.83       2
5       West    Denver 2,389.85       2
6       West   Seattle 1,999.98       1

New York has two orders worth $5,499.87, and Dallas also has two. Without as_index=False, you’d call .reset_index() afterward to get the same flat table, which is what you want before saving a DataFrame to CSV or charting.

If you’d rather see stores across the top as columns, that’s a reshape job; see these pandas pivot table examples or a pandas crosstab for counts.

Aggregate Sales by Month with a Date Column

Grouping by calendar month is a common report. Convert each date to a monthly period with dt.to_period("M") and group by that Series. If your dates arrive as text, start with converting strings to datetime in pandas.

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

month = df["order_date"].dt.to_period("M")
print(df.groupby(month)["revenue"].agg(["sum", "count"]))

Output:

                sum  count
order_date                
2026-01    9,999.78      4
2026-02    8,639.84      3
2026-03    3,909.66      3

January 2026 has four orders and the most revenue at $9,999.78, while February and March each have three. You can group by a Series that isn’t a column at all, as long as it lines up with the DataFrame’s index.

A monthly table like this also feeds straight into a stacked bar plot in pandas.

agg() vs transform(): When You Need Every Row Back

agg() returns one row per group. transform() returns a value for every original row, which lets you add a group total next to each order and compute its share:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

df["region_total"] = df.groupby("region")["revenue"].transform("sum")
df["share_pct"] = df["revenue"] / df["region_total"] * 100
print(df[["region", "store", "revenue", "share_pct"]].head(6))

Output:

      region     store  revenue  share_pct
0  Northeast    Boston 3,999.96      42.11
1  Northeast  New York 2,499.90      26.32
2  Northeast  New York 2,999.97      31.58
3      South   Atlanta 1,499.94      20.11
4      South    Dallas 4,999.95      67.03
5      South    Dallas   959.88      12.87

The Boston laptop order is 42.11% of Northeast revenue. Use transform() when the result goes back into the table as a new column; adding a column to a pandas DataFrame lists other ways to create one.

How pandas GroupBy Aggregation Handles Missing Values

Two kinds of missing data matter. A NaN inside a value column is skipped by most aggregations, and a missing group key drops the row unless you keep it. Here I blank one unit count and one region with the pandas loc indexer:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

df.loc[1, "units"] = None      # New York forgot to log units
df.loc[9, "region"] = None     # Chicago order has no region

print(df.groupby("region")["units"].agg(["count", "size", "sum"]))

Output:

           count  size   sum
region                      
Northeast      2     3  7.00
South          3     3 23.00
West           3     3 17.00
VS Code output of pandas groupby count vs size vs sum when one units value is missing and one region is blank
Northeast shows a count of 2 but a size of 3, and the Midwest disappears because its only order lost its region.

count skips the missing unit value, size counts every row, and sum ignores the gap. With the default dropna=True, the Chicago order vanishes because its key is missing.

To keep rows with a missing key as their own group, pass dropna=False to groupby(). To remove such rows on purpose instead, see dropping rows with NaN in pandas.

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

df.loc[9, "region"] = None     # Chicago order has no region
print(df.groupby("region", dropna=False)["revenue"].sum())

Output:

region
Northeast   9,499.83
South       7,459.77
West        4,389.83
NaN         1,199.85
Name: revenue, dtype: float64

The Chicago revenue of $1,199.85 now shows up under a NaN region instead of being dropped.

Common Errors in pandas GroupBy Aggregation

The error I hit most often comes from aggregating the whole DataFrame when it still has text columns:

import pandas as pd

pd.set_option("display.float_format", "{:,.2f}".format)
df = pd.DataFrame({
    "region": ["Northeast", "Northeast", "Northeast", "South", "South",
               "South", "West", "West", "West", "Midwest"],
    "store": ["Boston", "New York", "New York", "Atlanta", "Dallas",
              "Dallas", "Seattle", "Denver", "Denver", "Chicago"],
    "product": ["Laptop", "Monitor", "Laptop", "Monitor", "Laptop",
                "Headset", "Laptop", "Headset", "Monitor", "Headset"],
    "units": [4, 10, 3, 6, 5, 12, 2, 8, 7, 15],
    "revenue": [3999.96, 2499.90, 2999.97, 1499.94, 4999.95,
                959.88, 1999.98, 639.92, 1749.93, 1199.85],
    "order_date": pd.to_datetime([
        "2026-01-05", "2026-01-12", "2026-02-03", "2026-01-20",
        "2026-02-14", "2026-03-02", "2026-01-28", "2026-02-21",
        "2026-03-09", "2026-03-16"]),
})

try:
    df.groupby("region").mean()
except TypeError as e:
    print("TypeError:", str(e).splitlines()[0][:70])

print(df.groupby("region").mean(numeric_only=True))

Output:

TypeError: dtype 'str' does not support operation 'mean'
           units  revenue
region                   
Midwest    15.00 1,199.85
Northeast   5.67 3,166.61
South       7.67 2,486.59
West        5.67 1,463.28

Since pandas 2.0, mean() no longer drops text columns silently, so it raises a TypeError. Pass numeric_only=True, select the numeric columns first, or fix the dtype; changing a column data type in pandas helps when numbers were read as text.

  • KeyError in agg(): the column name in a tuple or dictionary is misspelled. Check df.columns.
  • TypeError: Must provide 'func' or tuples of '(column, aggfunc)': you called agg() with no arguments, or a named value isn’t a tuple.
  • Unexpected two-level columns: a dictionary or list produced a MultiIndex. Switch to named aggregation or flatten the names.
  • A lambda returns a list instead of one value: agg() needs a scalar per group, so use apply() for anything else.

These pandas guides pair well with grouped summaries:

Frequently Asked Questions

What is groupby aggregation in pandas?

It splits a DataFrame into groups with groupby() and reduces each group to one value, such as a sum or mean, with a method like sum() or with agg().

How do I apply multiple aggregation functions in pandas groupby?

Pass a list to agg(), like df.groupby("region")["revenue"].agg(["sum", "mean"]), or use named aggregation to set the output names.

What’s the difference between agg() and aggregate()?

None. agg() is an alias of aggregate(), and both accept a string, a function, a list or a dictionary.

How do I rename columns after a groupby aggregation?

Use named aggregation, such as agg(total=("revenue", "sum")), so the names are set in the same call. For dictionary results, join the MultiIndex tuples.

Why does count() differ from size() after groupby?

count() skips missing values in the column, while size() counts every row in the group, including rows with NaN.

Where is DataFrameGroupBy.agg documented?

See DataFrameGroupBy.agg() in the pandas docs.