Mathew K Analytics

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…

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.

📓 Full notebook

Download .ipynb

Pandas 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)
(8399, 21)
Order Date Region Product Category Sales Profit
33 10/10/2011 Nunavut Technology 426.037 -78.96
5281 9/15/2009 Prarie Furniture 2544.730 375.87
4912 1/12/2012 Prarie Office Supplies 31.350 -14.62
orders = df["Order ID"].nunique()
sales = df["Sales"].sum()
print(orders, round(sales, 2), round(sales / orders, 2))
5496 14915600.82 2713.9

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()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexes\base.py:3641, in Index.get_loc(self, key)
   3640 try:
-> 3641     return self._engine.get_loc(casted_key)
   3642 except KeyError as err:

File pandas/_libs/index.pyx:168, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/index.pyx:197, in pandas._libs.index.IndexEngine.get_loc()

File pandas/_libs/hashtable_class_helper.pxi:7668, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas/_libs/hashtable_class_helper.pxi:7676, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Category'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[4], line 1
----> 1 df["Category"].value_counts()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py:4378, in DataFrame.__getitem__(self, key)
   4376 if self.columns.nlevels > 1:
   4377     return self._getitem_multilevel(key)
-> 4378 indexer = self.columns.get_loc(key)
   4379 if is_integer(indexer):
   4380     indexer = [indexer]

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexes\base.py:3648, in Index.get_loc(self, key)
   3643     if isinstance(casted_key, slice) or (
   3644         isinstance(casted_key, abc.Iterable)
   3645         and any(isinstance(x, slice) for x in casted_key)
   3646     ):
   3647         raise InvalidIndexError(key) from err
-> 3648     raise KeyError(key) from err
   3649 except TypeError:
   3650     # If we have a listlike key, _check_indexing_error will raise
   3651     #  InvalidIndexError. Otherwise we fall through and re-raise
   3652     #  the TypeError.
   3653     self._check_indexing_error(key)

KeyError: 'Category'
print([c for c in df.columns if "Category" in c])
df["Product Category"].value_counts()
['Product Category', 'Product Sub-Category']
Product Category
Office Supplies    4610
Technology         2065
Furniture          1724
Name: count, dtype: int64
df.columns = (df.columns.str.lower()
              .str.replace(" ", "_")
              .str.replace("-", "_"))
print(df.columns[:8].tolist())
['row_id', 'order_id', 'order_date', 'order_priority', 'order_quantity', 'sales', 'discount', 'ship_mode']
df["order_date"] = pd.to_datetime(df["order_date"],
                                  format="%m/%d/%Y")
print(df["order_date"].min().date(), df["order_date"].max().date())
2009-01-01 2012-12-30
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)
count    8399.0
mean        2.0
std         2.3
min         0.0
25%         1.0
50%         2.0
75%         2.0
max        92.0
Name: ship_days, dtype: float64
df.groupby("ship_mode")["ship_days"].agg(["mean", "median"]).round(1)
mean median
ship_mode
Delivery Truck 2.0 2.0
Express Air 2.0 2.0
Regular Air 2.0 2.0
gaps = df.isna().sum()
gaps[gaps > 0]
product_base_margin    63
dtype: int64
print(df.duplicated().sum())
print(df["row_id"].is_unique)
0
True

Quick check: what share of order lines lose money?

loss = df["profit"] < 0
print(loss.sum(), round(loss.mean() * 100, 1))
4264 50.8

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))
14915601 1521768 10.2
orders = df["order_id"].nunique()
print(round(total_profit / orders, 2))
276.89

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))
-13.3
size = pd.qcut(df["sales"], 4, labels=["small", "medium", "large",
                                      "huge"])
by_size = df.groupby(size, observed=True)["margin_%"].mean()
by_size.round(1)
sales
small    -38.2
medium   -24.7
large      0.2
huge       9.6
Name: margin_%, dtype: float64
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)
sales profit margin_%
order_date
2009 4209139.5 434538.7 10.3
2010 3549680.8 363871.5 10.3
2011 3436816.7 381456.0 11.1
2012 3719963.9 341901.8 9.2

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")
sales profit margin_%
product_category
Furniture 5178590.5 117433.0 2.3
Office Supplies 3752762.1 518021.4 13.8
Technology 5984248.2 886313.5 14.8
cat = summarise(df, "product_category")[["sales", "profit"]]
(cat / cat.sum() * 100).round(1)
sales profit
product_category
Furniture 34.7 7.7
Office Supplies 25.2 34.0
Technology 40.1 58.2
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")
No description has been provided for this image
by_region = summarise(df, "region").sort_values("margin_%")
by_region
sales profit margin_%
region
Nunavut 116376.5 2841.1 2.4
Yukon 975867.4 73849.2 7.6
West 3597549.3 297008.6 8.3
Quebec 1510195.1 140426.6 9.3
Ontario 3063212.5 346868.5 11.3
Prarie 2837304.6 321160.1 11.3
Atlantic 2014248.2 238960.7 11.9
Northwest Territories 800847.3 100653.1 12.6

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]
sales profit margin_%
region
West 3597549.3 297008.6 8.3

Your turn: summarise by customer segment. Which has the best margin?

seg = summarise(df, "customer_segment")
seg.sort_values("margin_%", ascending=False)
sales profit margin_%
customer_segment
Small Business 2788321.0 315708.0 11.3
Corporate 5498904.9 599746.0 10.9
Consumer 3063611.1 287959.9 9.4
Home Office 3564763.9 318354.0 8.9

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")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[25], line 1
----> 1 df.pivot(index="region", columns="product_category",
      2          values="sales")

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py:10988, in DataFrame.pivot(self, columns, index, values)
  10981 @Substitution("")
  10982 @Appender(_shared_docs["pivot"])
  10983 def pivot(
  10984     self, *, columns, index=lib.no_default, values=lib.no_default
  10985 ) -> DataFrame:
  10986     from pandas.core.reshape.pivot import pivot
> 10988     return pivot(self, index=index, columns=columns, values=values)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\reshape\pivot.py:910, in pivot(data, columns, index, values)
    905         indexed = data._constructor_sliced(data[values]._values, index=multiindex)
    906 # error: Argument 1 to "unstack" of "DataFrame" has incompatible type "Union
    907 # [List[Any], ExtensionArray, ndarray[Any, Any], Index, Series]"; expected
    908 # "Hashable"
    909 # unstack with a MultiIndex returns a DataFrame
--> 910 result = cast("DataFrame", indexed.unstack(columns_listlike))  # type: ignore[arg-type]
    911 result.index.names = [
    912     name if name is not lib.no_default else None for name in result.index.names
    913 ]
    915 return result

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\series.py:4501, in Series.unstack(self, level, fill_value, sort)
   4451 """
   4452 Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
   4453 
   (...)
   4497 b    2    4
   4498 """
   4499 from pandas.core.reshape.reshape import unstack
-> 4501 return unstack(self, level, fill_value, sort)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\reshape\reshape.py:596, in unstack(obj, level, fill_value, sort)
    594 if is_1d_only_ea_dtype(obj.dtype):
    595     return _unstack_extension_series(obj, level, fill_value, sort=sort)
--> 596 unstacker = _Unstacker(
    597     obj.index, level=level, constructor=obj._constructor_expanddim, sort=sort
    598 )
    599 return unstacker.get_result(obj, value_columns=None, fill_value=fill_value)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\reshape\reshape.py:176, in _Unstacker.__init__(self, index, level, constructor, sort)
    168     if num_cells > np.iinfo(np.int32).max:
    169         warnings.warn(
    170             f"The following operation may generate {num_cells} cells "
    171             f"in the resulting pandas object.",
    172             PerformanceWarning,
    173             stacklevel=find_stack_level(),
    174         )
--> 176 self._make_selectors()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\reshape\reshape.py:232, in _Unstacker._make_selectors(self)
    229 mask.put(selector, True)
    231 if mask.sum() < len(self.index):
--> 232     raise ValueError("Index contains duplicate entries, cannot reshape")
    234 self.group_index = comp_index
    235 self.mask = mask

ValueError: Index contains duplicate entries, cannot reshape
pv = df.pivot_table(index="region", columns="product_category",
                    values="sales", aggfunc="sum",
                    margins=True, margins_name="Total")
(pv / 1000).round(0)
product_category Furniture Office Supplies Technology Total
region
Atlantic 709.0 478.0 827.0 2014.0
Northwest Territories 283.0 217.0 301.0 801.0
Nunavut 44.0 39.0 34.0 116.0
Ontario 1110.0 927.0 1026.0 3063.0
Prarie 919.0 720.0 1198.0 2837.0
Quebec 606.0 352.0 553.0 1510.0
West 1173.0 798.0 1627.0 3598.0
Yukon 336.0 222.0 418.0 976.0
Total 5179.0 3753.0 5984.0 14916.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
product_category Furniture Office Supplies Technology
region
Atlantic 2.2 14.0 18.9
Northwest Territories 2.6 17.1 18.7
Nunavut 8.0 -8.1 7.3
Ontario 1.8 16.5 16.9
Prarie 3.3 11.6 17.3
Quebec -0.1 12.2 17.8
West 2.6 14.6 9.2
Yukon 3.1 9.5 10.1
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")
No description has been provided for this image

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)
product_category Furniture Office Supplies Technology
order_date
2009 4.2 17.2 11.4
2010 0.8 13.0 17.0
2011 4.1 10.8 17.8
2012 -0.5 13.4 13.9

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")
sales profit margin_%
product_sub_category
Tables 1896008.1 -99062.5 -5.2
Bookcases 822652.0 -33582.1 -4.1
Scissors, Rulers and Trimmers 80996.3 -7799.2 -9.6
Rubber Bands 15006.6 -102.7 -0.7
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")
No description has been provided for this image
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)
sales profit margin_%
discount
0-3% 5679323.0 759244.0 13.4
3-6% 4050804.9 341965.8 8.4
6-9% 4038512.3 346596.4 8.6
9%+ 1146960.6 73961.8 6.4

Quick check: do tables lose money at every discount level?

is_table = df["product_sub_category"] == "Tables"
summarise(df[is_table], band[is_table])
sales profit margin_%
discount
0-3% 700866.4 -31804.7 -4.5
3-6% 492743.2 -21880.6 -4.4
6-9% 543771.0 -30289.0 -5.6
9%+ 158627.6 -15088.2 -9.5
by_product = df.groupby("product_name")["profit"].sum()
by_product.nsmallest(3).round(0)
product_name
Okidata Pacemark 4410N Wide Format Dot Matrix Printer   -43949.0
Canon imageCLASS 2200 Advanced Copier                   -31886.0
Global High-Back Leather Tilter, Burgundy               -30519.0
Name: profit, dtype: float64

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())
48 0
ax = (monthly / 1000).plot(figsize=(9, 4))
ax.set_title("Monthly sales and profit")
ax.set_xlabel("Month")
ax.set_ylabel("Thousand dollars")
No description has been provided for this image
monthly["margin_%"] = monthly["profit"] / monthly["sales"] * 100
print(monthly["margin_%"].round(1).agg(["min", "median", "max"]))
print(monthly["margin_%"].idxmin().strftime("%B %Y"))
min        0.5
median    10.8
max       16.0
Name: margin_%, dtype: float64
March 2010
trend = monthly["profit"].rolling(12).mean() / 1000
trend.dropna().round(1).iloc[[0, -1]]
order_date
2009-12-31    36.2
2012-12-31    28.5
Freq: 36ME, Name: profit, dtype: float64

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())
12 367.0
6 258.0

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))
['Bookcases', 'Rubber Bands', 'Scissors, Rulers and Trimmers', 'Tables']
18.9
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))
10.2 13.7
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()
No description has been provided for this image
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)
Furniture Office Supplies Technology
region
Atlantic 2.2 14.0 18.9
Northwest Territories 2.6 17.1 18.7
Nunavut 8.0 -8.1 7.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}%")
Tables lost $99,062; without the loss-makers margin rises from 10.2% to 13.7%

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#

  1. Build a margin grid of customer segment by product category.
  2. Find the five customers who generated the most profit.
  3. 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.