Group By to Pivot Table – Converting GroupBy Results to Pivot Tables in Pandas 2026
Many data manipulation tasks start with a groupby() and then need to be reshaped into a pivot table format for reporting or visualization. In 2026, understanding how to smoothly transition from GroupBy aggregations to beautiful pivot tables is a highly valuable skill.
TL;DR — Two Main Approaches
- Do aggregation with
groupby().agg()→ then.unstack() - Use
pivot_table()directly (often cleaner and more flexible)
1. Starting with GroupBy and Converting to Pivot
import pandas as pd
df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
# Step 1: GroupBy aggregation
grouped = (
df
.groupby(["region", df["order_date"].dt.to_period("M").rename("month")])
.agg(total_sales=("amount", "sum"))
.reset_index()
)
# Step 2: Convert to Pivot Table format
pivot = grouped.pivot(
index="region",
columns="month",
values="total_sales"
).round(2)
print(pivot)
2. Cleaner Approach: Direct pivot_table() (Recommended)
# Much cleaner and more powerful
pivot = pd.pivot_table(
df,
values="amount",
index="region",
columns=df["order_date"].dt.to_period("M").rename("month"),
aggfunc="sum",
margins=True,
margins_name="Total"
).round(2)
print(pivot)
3. Advanced Example: Multiple Metrics in Pivot Form
report = pd.pivot_table(
df,
values=["amount", "quantity"],
index=["region", "category"],
columns=df["order_date"].dt.to_period("M").rename("month"),
aggfunc={
"amount": ["sum", "mean"],
"quantity": "sum"
},
margins=True
).round(2)
print(report)
4. Best Practices in 2026
- Use
pivot_table()directly when possible — it is usually cleaner than groupby + unstack - Use
groupby().agg()+.unstack()only when you need very custom logic before pivoting - Extract date components with
.dt.to_period()for clean month/year columns - Add
margins=Trueto get grand totals automatically - Use named aggregation inside
pivot_table()when you need multiple metrics
Conclusion
Converting GroupBy results into pivot table format is a very common workflow in data manipulation. In 2026, the recommended approach is to use pd.pivot_table() directly whenever possible because it is more concise, flexible, and readable than doing a groupby followed by unstack. Mastering both techniques gives you full control over how you reshape and present your data.
Next steps:
- Take a GroupBy summary you currently use and convert it into a clean pivot table using
pivot_table()