Lesson 62 · Pandas Full Course
Sales and Profit Dashboard in Pandas: Find Where Profit Leaks | Pandas Course #62
In this lesson you'll be able to: Prepare a sales table with tidy names and real dates Summarise sales, profit and margin the right way Break results down…
- CoursePandas Full Course
- Lesson62 of 65
- FormatJupyter notebook · 43 code cells
- Data1 dataset
What you'll learn
Datasets used in this lesson
Save these next to the notebook. In Google Colab, upload them with the 📁 icon on the left first.
- superstore.csv preview1.7 MB
📓 Full notebook
Download .ipynbPandas 62: Hands-on Project - Sales and Profit Summary Dashboard#
In this lesson you'll be able to:
- Prepare a sales table with tidy names and real dates
- Summarise sales, profit and margin the right way
- Break results down with groupby and pivot tables
- Find the products and discounts that leak profit
- Combine the key charts into a one-page dashboard Data: four years of office superstore orders (superstore.csv)
Warm-up: headline KPIs#
Lesson 61 built KPIs. Here are three of them for a new shop.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data/pandas/superstore.csv")
print(df.shape)
cols = ["Order Date", "Region", "Product Category", "Sales", "Profit"]
df[cols].sample(3, random_state=42)
orders = df["Order ID"].nunique()
sales = df["Sales"].sum()
print(orders, round(sales, 2), round(sales / orders, 2))
Prepare the sales table#
Problem: long names with spaces slow down every line we type.
Common mistake: guessing a column name instead of checking it.
df["Category"].value_counts()
print([c for c in df.columns if "Category" in c])
df["Product Category"].value_counts()
df.columns = (df.columns.str.lower()
.str.replace(" ", "_")
.str.replace("-", "_"))
print(df.columns[:8].tolist())
df["order_date"] = pd.to_datetime(df["order_date"],
format="%m/%d/%Y")
print(df["order_date"].min().date(), df["order_date"].max().date())
df["ship_date"] = pd.to_datetime(df["ship_date"], format="%m/%d/%Y")
df["ship_days"] = (df["ship_date"] - df["order_date"]).dt.days
df["ship_days"].describe().round(1)
df.groupby("ship_mode")["ship_days"].agg(["mean", "median"]).round(1)
gaps = df.isna().sum()
gaps[gaps > 0]
print(df.duplicated().sum())
print(df["row_id"].is_unique)
Quick check: what share of order lines lose money?
loss = df["profit"] < 0
print(loss.sum(), round(loss.mean() * 100, 1))
Summarise sales, profit and margin#
Problem: sales can flatter a business; margin shows what it keeps.
total_sales = df["sales"].sum()
total_profit = df["profit"].sum()
margin = total_profit / total_sales * 100
print(round(total_sales), round(total_profit), round(margin, 1))
orders = df["order_id"].nunique()
print(round(total_profit / orders, 2))
Quick check: is the overall margin the average of each line's margin?
df["margin_%"] = df["profit"] / df["sales"] * 100
print(round(df["margin_%"].mean(), 1))
size = pd.qcut(df["sales"], 4, labels=["small", "medium", "large",
"huge"])
by_size = df.groupby(size, observed=True)["margin_%"].mean()
by_size.round(1)
yearly = df.resample("YE", on="order_date")[["sales", "profit"]].sum()
yearly["margin_%"] = yearly["profit"] / yearly["sales"] * 100
yearly.index = yearly.index.year
yearly.round(1)
Break totals down by category and region#
Problem: find which parts of the business earn the profit.
def summarise(data, by):
cols = ["sales", "profit"]
out = data.groupby(by, observed=True)[cols].sum()
out["margin_%"] = out["profit"] / out["sales"] * 100
return out.round(1)
summarise(df, "product_category")
cat = summarise(df, "product_category")[["sales", "profit"]]
(cat / cat.sum() * 100).round(1)
ax = (cat / 1000).plot.bar(rot=0, figsize=(8, 4))
ax.set_title("Sales and profit by category")
ax.set_xlabel("Product category")
ax.set_ylabel("Thousand dollars")
by_region = summarise(df, "region").sort_values("margin_%")
by_region
Quick check: which big region earns a below-average margin?
big = by_region["sales"] > by_region["sales"].median()
weak = by_region["margin_%"] < margin
by_region[big & weak]
Your turn: summarise by customer segment. Which has the best margin?
seg = summarise(df, "customer_segment")
seg.sort_values("margin_%", ascending=False)
Build pivot-table summaries#
Problem: see two breakdowns at once, region by category, in one grid.
Common mistake: using pivot when pairs repeat.
df.pivot(index="region", columns="product_category",
values="sales")
pv = df.pivot_table(index="region", columns="product_category",
values="sales", aggfunc="sum",
margins=True, margins_name="Total")
(pv / 1000).round(0)
args = dict(index="region", columns="product_category",
aggfunc="sum")
sales_pv = df.pivot_table(values="sales", **args)
profit_pv = df.pivot_table(values="profit", **args)
margin_pv = (profit_pv / sales_pv * 100).round(1)
margin_pv
import seaborn as sns
ax = sns.heatmap(margin_pv, annot=True, fmt=".1f", cmap="RdYlGn",
center=0)
ax.set_title("Profit margin (%) by region and category")
ax.set_xlabel("Product category")
ax.set_ylabel("Region")
Quick check: is furniture's margin getting better or worse each year?
year = df["order_date"].dt.year
yr = dict(index=year, columns="product_category", aggfunc="sum")
yr_margin = (df.pivot_table(values="profit", **yr)
/ df.pivot_table(values="sales", **yr) * 100)
yr_margin.round(1)
Find where the profit leaks#
Problem: a healthy total can hide products that lose money.
by_sub = summarise(df, "product_sub_category")
by_sub.nsmallest(4, "profit")
ax = (by_sub["profit"] / 1000).sort_values().plot.barh(
figsize=(8, 6))
ax.set_title("Profit by sub-category")
ax.set_xlabel("Profit (thousand dollars)")
ax.set_ylabel("Sub-category")
names = ["0-3%", "3-6%", "6-9%", "9%+"]
band = pd.cut(df["discount"], bins=[0, 0.03, 0.06, 0.09, 0.25],
labels=names, include_lowest=True)
summarise(df, band)
Quick check: do tables lose money at every discount level?
is_table = df["product_sub_category"] == "Tables"
summarise(df[is_table], band[is_table])
by_product = df.groupby("product_name")["profit"].sum()
by_product.nsmallest(3).round(0)
Track sales and profit month by month#
Problem: yearly totals hide the swings a manager needs to see.
monthly = df.resample("ME", on="order_date")[["sales", "profit"]]
monthly = monthly.sum()
print(len(monthly), (monthly['profit'] < 0).sum())
ax = (monthly / 1000).plot(figsize=(9, 4))
ax.set_title("Monthly sales and profit")
ax.set_xlabel("Month")
ax.set_ylabel("Thousand dollars")
monthly["margin_%"] = monthly["profit"] / monthly["sales"] * 100
print(monthly["margin_%"].round(1).agg(["min", "median", "max"]))
print(monthly["margin_%"].idxmin().strftime("%B %Y"))
trend = monthly["profit"].rolling(12).mean() / 1000
trend.dropna().round(1).iloc[[0, -1]]
Your turn: which calendar month sells the most on average?
month_no = monthly.index.month
avg = monthly.groupby(month_no)["sales"].mean() / 1000
print(avg.round(0).idxmax(), avg.round(0).max())
print(avg.round(0).idxmin(), avg.round(0).min())
Mini-project: what if the loss-makers were fixed?#
Question: how much would the margin improve without loss-making lines? Plan: list them, recalculate, then build a one-page dashboard.
losers = by_sub.index[by_sub["profit"] < 0]
print(list(losers))
share = by_sub.loc[losers, "sales"].sum() / total_sales * 100
print(round(share, 1))
keep = df[~df["product_sub_category"].isin(losers)]
new_margin = keep["profit"].sum() / keep["sales"].sum() * 100
print(round(margin, 1), round(new_margin, 1))
fig, axes = plt.subplots(2, 2, figsize=(11, 8))
cat = summarise(df, "product_category")
(cat["sales"] / 1000).plot.bar(ax=axes[0, 0], rot=0,
title="Sales by category", xlabel="", ylabel="Thousand $")
by_region["margin_%"].plot.barh(ax=axes[0, 1], xlabel="Region",
title="Margin by region", ylabel="")
(monthly["profit"] / 1000).plot(ax=axes[1, 0], xlabel="Month",
title="Monthly profit", ylabel="Thousand $")
summarise(df, band)["margin_%"].plot.bar(ax=axes[1, 1], rot=0,
title="Margin by discount", xlabel="Discount", ylabel="%")
fig.tight_layout()
import os
os.makedirs("output/pandas", exist_ok=True)
by_region.to_csv("output/pandas/l62_region_summary.csv")
margin_pv.to_csv("output/pandas/l62_margin_grid.csv")
back = pd.read_csv("output/pandas/l62_margin_grid.csv",
index_col=0)
back.head(3)
worst = by_sub["profit"].idxmin()
loss_amt = -by_sub.loc[worst, "profit"]
print(f"{worst} lost ${loss_amt:,.0f}; without the loss-makers "
f"margin rises from {margin:.1f}% to {new_margin:.1f}%")
Recap#
- Check column names, tidy them, and parse dates first
- Margin = total profit / total sales, never a mean of line margins
- One summary function keeps every table consistent
- pivot_table aggregates repeated pairs; pivot only reshapes
- Sub-categories and discount bands show where profit leaks
Challenges#
- Build a margin grid of customer segment by product category.
- Find the five customers who generated the most profit.
- Compare margins by ship mode. Which mode earns the most?
What's next#
Lesson 63: Hands-on Project - Business Insights Report Turn analysis like today's into clear written findings.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



