Sample DataFrame context
A sales table with region, product and revenue columns.
Syntax or pattern
df.groupby("region")["revenue"].sum()5 practical examples
Total sales by region
Summarize revenue by region.
summary = sales.groupby("region", as_index=False)["revenue"].sum()The output has one row per region with total revenue.
Multiple metrics by region
Create several KPI columns in one groupby.
summary = sales.groupby("region").agg(
total_sales=("revenue", "sum"),
orders=("order_id", "nunique"),
avg_order=("revenue", "mean")
).reset_index()The report includes total sales, order count and average order value.
Group by month and region
Build a monthly regional sales table.
monthly = sales.groupby(["month", "region"], as_index=False)["revenue"].sum()This is useful for charts and dashboards.
Count customers by segment
Count unique customers in each segment.
segment = sales.groupby("segment")["customer_id"].nunique().reset_index(name="customers")The result shows customer count per segment.
Sort the grouped output
Show the largest groups first.
summary = summary.sort_values("total_sales", ascending=False)The most important regions appear at the top.
Common mistakes to avoid
- Changing the original DataFrame before checking the result.
- Forgetting to inspect row counts before and after the operation.
- Using a pattern without confirming column names and data types.
FAQ
What is the main use of groupby Examples?
Group sales, customers and operations data by category, region, date or status.
Should I use this in a notebook or a script?
Both work. Use a notebook while exploring the data, then move the final workflow into a repeatable script when it is stable.
How do I avoid breaking my source data?
Create a copy of the DataFrame before transforming it and check row counts, missing values and sample rows after each important step.