Grouping by Multiple Variables in Pandas – Multi-Level GroupBy Best Practices 2026
Grouping data by multiple variables (columns) is one of the most powerful features in Pandas. It allows you to create rich, multi-dimensional summaries such as sales by region and month, user behavior by category and country, or performance by department and quarter.
TL;DR — Modern Multi-Variable Grouping
- Use
groupby([col1, col2, ...])for multiple grouping keys - Combine with date components using
.dtaccessor - Use named aggregation with
.agg()for clean output - Apply method chaining for readability
1. Basic Grouping by Multiple Columns
import pandas as pd
# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
"order_date": pd.date_range("2025-10-01", periods=n, freq="3D"),
"customer_id": rng.integers(101, 121, n),
"customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
"product_id": rng.integers(1, 9, n),
"region": rng.choice(["North", "South", "East", "West"], n),
"category": rng.choice(["Electronics", "Books", "Home"], n),
"payment_method": rng.choice(["card", "cash", "wallet"], n),
"segment": rng.choice(["consumer", "business"], n),
"quantity": rng.integers(1, 6, n),
"amount": rng.uniform(50, 2500, n).round(2),
}).assign(
ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
# Group by region and category
summary = (
df
.groupby(["region", "category"])
.agg(
total_sales=("amount", "sum"),
avg_sale=("amount", "mean"),
order_count=("amount", "count"),
unique_customers=("customer_id", "nunique")
)
.round(2)
.reset_index()
)
print(summary)
2. Advanced Multi-Level Grouping with Date Components
multi_summary = (
df
.groupby([
"region",
"category",
df["order_date"].dt.to_period("M").rename("month")
])
.agg(
total_sales=("amount", "sum"),
average_order_value=("amount", "mean"),
transaction_count=("amount", "count"),
unique_customers=("customer_id", "nunique")
)
.round(2)
.reset_index()
)
print(multi_summary)
3. Grouping by Multiple Variables Including Time Hierarchy
report = (
df
.groupby([
"region",
df["order_date"].dt.year.rename("year"),
df["order_date"].dt.quarter.rename("quarter")
])
.agg(
total_revenue=("amount", "sum"),
avg_revenue=("amount", "mean"),
num_orders=("amount", "count")
)
.round(2)
.reset_index()
)
4. Best Practices in 2026
- Use a list of columns inside
groupby()for multiple grouping keys - Combine categorical columns with date components extracted via
.dt - Always use named aggregation (
total_sales=("amount", "sum")) for clear column names - Use method chaining to keep complex groupings readable
- Apply
.reset_index()at the end when you need a flat DataFrame - Round results for professional-looking reports
Why Group by More Than One Column
Grouping by several columns creates one group for every combination of values that actually appears in the data, such as each region and category pair. The result has a MultiIndex, and its first level is the outer grouping. This structure is ideal for drilling down: you can look at totals by region, then by category inside each region.
unstack() turns the inner level into columns, which gives a cross-table that is easier to read, while reset_index() gives a long table that is easier to filter and plot.
Worked Example: From Long to Wide
This example groups by two keys, then reshapes the result for reading.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"category": ["Books", "Toys", "Books", "Books", "Toys"],
"amount": [100, 40, 60, 30, 80],
})
long = df.groupby(["region", "category"])["amount"].sum()
print(long)
wide = long.unstack(fill_value=0)
print(wide)
# category Books Toys
# region
# North 100 40
# South 90 80
The long form lists each combination once; the wide form puts categories side by side for comparison.
Common Mistakes
- Expecting every combination: missing pairs do not appear unless you reindex or use
fill_valueafterunstack() - Ordering keys carelessly: the first key becomes the outer level
- Forgetting
observed=Truewith categorical keys, which otherwise creates empty combinations - Too many keys: very fine groups contain one row each and summarise nothing
Quick Summary
- Pass a list of columns to
groupby() - Use
unstack()for wide tables - Use
reset_index()for long, tidy tables
Conclusion
Grouping by multiple variables unlocks deep insights from your data. In 2026, mastering multi-level groupby() with named aggregation allows you to create sophisticated, multi-dimensional summaries with clean and maintainable code. Whether you are analyzing sales by region + product category + month or user engagement by country + device type, this technique is essential for effective data manipulation.
Next steps:
- Choose two or more columns in your dataset that make sense to group together and build a multi-variable summary using the patterns above