Lesson 63 · Pandas Full Course
Turn Data into a Business Insights Report with Pandas (Analyst Project) | Pandas Course #63
In this lesson you'll be able to: Turn a manager's vague questions into precise pandas questions Find where profit comes from, and where it leaks away Link…
- CoursePandas Full Course
- Lesson63 of 65
- FormatJupyter notebook · 39 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 63: Hands-on Project - Business Insights Report#
In this lesson you'll be able to:
- Turn a manager's vague questions into precise pandas questions
- Find where profit comes from, and where it leaks away
- Link losses to discounts, products and shipping
- Track sales and profit over time
- Write the findings into a short report file Dataset: a Canadian office superstore, 8,399 order lines (data/pandas/superstore.csv)
Warm-up: the dashboard headline#
Lesson 62 built a sales and profit dashboard. Start from its headline numbers.
import pandas as pd
df = pd.read_csv("data/pandas/superstore.csv")
print(df.shape)
df[["Order Date", "Sales", "Profit", "Region"]].head(3)
sales = df["Sales"].sum()
profit = df["Profit"].sum()
print(f"Sales: {sales:,.0f}")
print(f"Profit: {profit:,.0f}")
print(f"Margin: {profit / sales:.1%}")
Prepare the data for a report#
Problem: the questions are vague and the dates are still text.
The manager asks:
- Where does our profit come from?
- What is losing us money?
- Are we growing?
df[["Order Date", "Ship Date"]].dtypes
Common mistake: guessing the date format
pd.to_datetime(df["Order Date"], format="%d/%m/%Y")
for col in ["Order Date", "Ship Date"]:
df[col] = pd.to_datetime(df[col], format="%m/%d/%Y")
print(df["Order Date"].min(), df["Order Date"].max())
df["year"] = df["Order Date"].dt.year
df["ship_days"] = (df["Ship Date"] - df["Order Date"]).dt.days
df["margin"] = df["Profit"] / df["Sales"]
df[["year", "ship_days", "margin"]].describe().round(2)
cols = ["Product Sub-Category", "Discount", "Profit", "margin"]
df[cols].sample(3, random_state=42).round(2)
missing = df.isna().sum()
print(missing[missing > 0])
print(df.duplicated().sum())
Quick check: what share of order lines made a loss? Guess first.
loss_share = (df["Profit"] < 0).mean()
print(f"{loss_share:.1%} of order lines lost money")
Find where the profit comes from#
Problem: one total hides which parts of the business earn it.
region = df.groupby("Region")[["Sales", "Profit"]].sum()
region["margin"] = region["Profit"] / region["Sales"]
region.sort_values("Profit", ascending=False).round(3)
cat = df.groupby("Product Category")[["Sales", "Profit"]].sum()
share = cat / cat.sum()
share.round(3)
import matplotlib.pyplot as plt
ax = share.plot(kind="bar", rot=0, figsize=(7, 4))
ax.set_title("Share of sales and profit by category")
ax.set_xlabel("Product category")
ax.set_ylabel("Share of total")
plt.show()
Quick check: which category keeps the most profit per dollar of sales?
cat_margin = cat["Profit"] / cat["Sales"]
cat_margin.sort_values(ascending=False).round(3)
Common mistake: assuming a column name from another dataset
df.groupby("Category")["Profit"].sum()
print([c for c in df.columns if "Category" in c])
df.groupby("Product Category")["Profit"].sum().round(0)
Your turn#
List the 5 customers who brought in the most profit.
by_customer = df.groupby("Customer Name")["Profit"].sum()
by_customer.nlargest(5).round(0)
Find what is losing money#
Problem: half the lines lose money. Which products, and why?
sub = df.groupby("Product Sub-Category")[["Sales", "Profit"]].sum()
sub.sort_values("Profit").head(5).round(0)
lookup = df[["Product Sub-Category", "Product Category"]]
lookup = lookup.drop_duplicates()
losers = sub[sub["Profit"] < 0].sort_values("Profit")
losers = losers.reset_index()
losers.merge(lookup, on="Product Sub-Category").round(0)
Common mistake: joining two conditions with and
df[df["Profit"] < 0 and df["Discount"] > 0.08]
deep = df[(df["Profit"] < 0) & (df["Discount"] > 0.08)]
print(len(deep))
print(round(deep["Profit"].sum()))
edges = [0, 0.03, 0.06, 0.09, 0.25]
labels = ["0-3%", "3-6%", "6-9%", "9%+"]
df["disc_band"] = pd.cut(df["Discount"], edges, labels=labels,
include_lowest=True)
bands = df.groupby("disc_band", observed=True).agg(
lines=("Profit", "size"),
loss_share=("Profit", lambda p: (p < 0).mean()),
avg_profit=("Profit", "mean"),
)
bands.round(3)
ax = bands["loss_share"].plot(kind="bar", rot=0, figsize=(7, 4))
ax.set_title("Share of order lines that lost money")
ax.set_xlabel("Discount band")
ax.set_ylabel("Share of lines with a loss")
plt.show()
Your turn#
Which ship mode has the highest share of loss-making lines?
is_loss = df["Profit"] < 0
is_loss.groupby(df["Ship Mode"]).mean().round(3)
Compare segments and shipping in one grid#
Problem: managers read grids faster than long lists.
grid = df.pivot_table(index="Customer Segment",
columns="Product Category",
values="Profit", aggfunc="sum")
grid.round(0)
Quick check: which segment and category pair earns the least?
cells = grid.stack()
print(cells.idxmin(), round(cells.min()))
ship = df.groupby("Ship Mode")[["Shipping Cost", "ship_days"]]
ship.mean().round(2)
mix = pd.crosstab(df["Order Priority"], df["Ship Mode"],
normalize="index")
mix.round(2)
days = df.groupby("Order Priority")["ship_days"].median()
days.sort_values()
Track sales and profit over time#
Problem: totals by year and month show the direction of travel.
yearly = df.groupby("year")[["Sales", "Profit"]].sum()
yearly["sales_growth"] = yearly["Sales"].pct_change()
yearly.round(3)
by_year = df.pivot_table(index="year", columns="Product Category",
values="Profit", aggfunc="sum")
by_year.round(0)
Your turn#
Find furniture's yearly sales growth. Is it selling less, or just earning less?
furn = df[df["Product Category"] == "Furniture"]
furn_sales = furn.groupby("year")["Sales"].sum()
furn_sales.pct_change().round(3)
Common mistake: resampling without a date index
df["Sales"].resample("ME").sum()
by_date = df.set_index("Order Date")
monthly = by_date["Sales"].resample("ME").sum()
print(len(monthly))
print(monthly.idxmax().date(), round(monthly.max()))
print(monthly.idxmin().date(), round(monthly.min()))
smooth = monthly.rolling(3).mean()
ax = monthly.plot(figsize=(8, 4), alpha=0.4, label="Monthly")
smooth.plot(ax=ax, label="3-month average")
ax.set_title("Superstore sales by month")
ax.set_xlabel("Month")
ax.set_ylabel("Sales")
ax.legend()
plt.show()
Quick check: is there a busy quarter of the year?
quarter = df["Order Date"].dt.quarter
df.groupby(quarter)["Sales"].sum().round(0)
Mini-project: write the insights report#
Question: what would fixing the loss-makers be worth?
Plan: size the problem, build a findings table, save it, read it back.
bad = losers["Product Sub-Category"]
rest = df[~df["Product Sub-Category"].isin(bad)]
new_margin = rest["Profit"].sum() / rest["Sales"].sum()
print(f"Margin now: {profit / sales:.1%}")
print(f"Without loss-makers: {new_margin:.1%}")
findings = pd.DataFrame({
"question": ["Profit source", "Biggest leak", "Loss lines",
"Margin if fixed"],
"finding": [cat_margin.idxmax(), bad.iloc[0],
f"{loss_share:.1%}", f"{new_margin:.1%}"],
})
findings
import os
os.makedirs("output/pandas", exist_ok=True)
path = "output/pandas/l63_insights.csv"
findings.to_csv(path, index=False)
pd.read_csv(path)
loss_total = losers["Profit"].sum()
names = "; ".join(bad)
print(f"Loss-makers: {names}")
print(f"Lost in total: {loss_total:,.0f}")
Recap#
- Turn vague questions into groupby, pivot and time questions
- Parse dates with an explicit format before any time analysis
- Margins and shares compare big and small groups fairly
- Combine conditions with & and brackets, never with and
- Build reports from calculated values, then save and re-read them
Challenges#
- Add a finding for the most profitable province.
- Which order priority has the lowest average margin?
- Rebuild the discount band table for furniture lines only.
What's next#
Lesson 64: Hands-on Project - Predicting House Prices Prepare real housing data and fit a first price model.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



