Skip to content

pandas groupby explained with examples

November 2, 2026 · 1 min read

Use groupby to split a DataFrame into groups, then pick a column and a calculation: df.groupby("product")["total"].sum() gives one total per product. Add .agg() when you want several statistics at once.

Totals and a summary table

import pandas as pd

sales = pd.DataFrame({
    "product": ["Tea", "Mug", "Tea", "Mug", "Jar", "Tea"],
    "qty": [2, 1, 3, 4, 1, 1],
    "price": [4.0, 9.0, 4.0, 9.0, 12.0, 4.0],
})
sales["total"] = sales["qty"] * sales["price"]

print(sales.groupby("product")["total"].sum())

summary = sales.groupby("product").agg(
    revenue=("total", "sum"),
    avg_order=("total", "mean"),
    orders=("total", "count"),
)
print(summary)

Output:

Output
product
Jar    12.0
Mug    45.0
Tea    24.0
Name: total, dtype: float64
         revenue  avg_order  orders
product                            
Jar         12.0       12.0       1
Mug         45.0       22.5       2
Tea         24.0        8.0       3

How it works

groupby works in three steps: it splits the rows by product, applies a calculation to each group, and combines the answers into one result.

  • groupby("product") makes one group per product name.
  • ["total"] picks the column to calculate on.
  • .sum() totals that column inside each group.

With .agg(), each keyword argument becomes a column in the result. It is set to a tuple of (column to use, calculation to do). Here revenue is the sum of total, avg_order is the mean, and orders counts the rows.

The groups come out sorted by name, and the product names become the index. Call summary.reset_index() if you want product back as a normal column.

Common mistake

Skipping the column selection:

sales.groupby("product").sum()

This sums every column, including qty and price, and the price sum is meaningless. In some cases it fails on text columns. Select the column you care about first, as in sales.groupby("product")["total"].sum().

Takeaway

groupby splits, calculates and combines in one line. Add .agg() with named results to get a whole summary table.

More on Data Science