Mathew K Analytics

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…

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 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)
(8399, 21)
Order Date Sales Profit Region
0 10/13/2010 261.54 -213.25 Nunavut
1 10/1/2012 10123.02 457.81 Nunavut
2 10/1/2012 244.57 46.71 Nunavut
sales = df["Sales"].sum()
profit = df["Profit"].sum()
print(f"Sales:  {sales:,.0f}")
print(f"Profit: {profit:,.0f}")
print(f"Margin: {profit / sales:.1%}")
Sales:  14,915,601
Profit: 1,521,768
Margin: 10.2%

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
Order Date    str
Ship Date     str
dtype: object

Common mistake: guessing the date format

pd.to_datetime(df["Order Date"], format="%d/%m/%Y")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[5], line 1
----> 1 pd.to_datetime(df["Order Date"], format="%d/%m/%Y")

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py:1036, in to_datetime(arg, errors, dayfirst, yearfirst, utc, format, exact, unit, origin, cache)
   1034             result = arg.tz_localize("utc")
   1035 elif isinstance(arg, ABCSeries):
-> 1036     cache_array = _maybe_cache(arg, format, cache, convert_listlike)
   1037     if not cache_array.empty:
   1038         result = arg.map(cache_array)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py:254, in _maybe_cache(arg, format, cache, convert_listlike)
    252 unique_dates = unique(arg)
    253 if len(unique_dates) < len(arg):
--> 254     cache_dates = convert_listlike(unique_dates, format)
    255     # GH#45319
    256     try:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py:435, in _convert_listlike_datetimes(arg, format, name, utc, unit, errors, dayfirst, yearfirst, exact)
    433 # `format` could be inferred, or user didn't ask for mixed-format parsing.
    434 if format is not None and format != "mixed":
--> 435     return _array_strptime_with_fallback(arg, name, utc, format, exact, errors)
    437 result, tz_parsed = objects_to_datetime64(
    438     arg,
    439     dayfirst=dayfirst,
   (...)
    443     allow_object=True,
    444 )
    446 if tz_parsed is not None:
    447     # We can take a shortcut since the datetime64 numpy array
    448     # is in UTC

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\tools\datetimes.py:470, in _array_strptime_with_fallback(arg, name, utc, fmt, exact, errors)
    459 def _array_strptime_with_fallback(
    460     arg,
    461     name,
   (...)
    465     errors: str,
    466 ) -> Index:
    467     """
    468     Call array_strptime, with fallback behavior depending on 'errors'.
    469     """
--> 470     result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc)
    471     if tz_out is not None:
    472         unit = np.datetime_data(result.dtype)[0]

File pandas/_libs/tslibs/strptime.pyx:564, in pandas._libs.tslibs.strptime.array_strptime()

File pandas/_libs/tslibs/strptime.pyx:512, in pandas._libs.tslibs.strptime.array_strptime()

File pandas/_libs/tslibs/strptime.pyx:618, in pandas._libs.tslibs.strptime._parse_with_format()

ValueError: time data "10/13/2010" doesn't match format "%d/%m/%Y". You might want to try:
    - passing `format` if your strings have a consistent format;
    - passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
    - passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.
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())
2009-01-01 00:00:00 2012-12-30 00:00:00
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)
year ship_days margin
count 8399.00 8399.00 8399.00
mean 2010.48 2.03 -0.13
std 1.12 2.30 0.61
min 2009.00 0.00 -11.44
25% 2009.00 1.00 -0.34
50% 2010.00 2.00 -0.01
75% 2012.00 2.00 0.22
max 2012.00 92.00 0.98
cols = ["Product Sub-Category", "Discount", "Profit", "margin"]
df[cols].sample(3, random_state=42).round(2)
Product Sub-Category Discount Profit margin
33 Telephones and Communication 0.01 -78.96 -0.19
5281 Office Furnishings 0.02 375.87 0.15
4912 Binders and Binder Accessories 0.03 -14.62 -0.47
missing = df.isna().sum()
print(missing[missing > 0])
print(df.duplicated().sum())
Product Base Margin    63
dtype: int64
0

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")
50.8% 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)
Sales Profit margin
Region
Ontario 3063212.480 346868.54 0.113
Prarie 2837304.602 321160.12 0.113
West 3597549.276 297008.61 0.083
Atlantic 2014248.204 238960.66 0.119
Quebec 1510195.080 140426.65 0.093
Northwest Territories 800847.330 100653.08 0.126
Yukon 975867.371 73849.21 0.076
Nunavut 116376.484 2841.11 0.024
cat = df.groupby("Product Category")[["Sales", "Profit"]].sum()
share = cat / cat.sum()
share.round(3)
Sales Profit
Product Category
Furniture 0.347 0.077
Office Supplies 0.252 0.340
Technology 0.401 0.582
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()
No description has been provided for this image

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)
Product Category
Technology         0.148
Office Supplies    0.138
Furniture          0.023
dtype: float64

Common mistake: assuming a column name from another dataset

df.groupby("Category")["Profit"].sum()
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[15], line 1
----> 1 df.groupby("Category")["Profit"].sum()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\util\_decorators.py:336, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    330 if len(args) > num_allow_args:
    331     warnings.warn(
    332         msg.format(arguments=_format_argument_list(allow_args)),
    333         klass,
    334         stacklevel=find_stack_level(),
    335     )
--> 336 return func(*args, **kwargs)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py:10835, in DataFrame.groupby(self, by, level, as_index, sort, group_keys, observed, dropna)
  10832 if level is None and by is None:
  10833     raise TypeError("You have to supply one of 'by' and 'level'")
> 10835 return DataFrameGroupBy(
  10836     obj=self,
  10837     keys=by,
  10838     level=level,
  10839     as_index=as_index,
  10840     sort=sort,
  10841     group_keys=group_keys,
  10842     observed=observed,
  10843     dropna=dropna,
  10844 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\groupby.py:1095, in GroupBy.__init__(self, obj, keys, level, grouper, exclusions, selection, as_index, sort, group_keys, observed, dropna)
   1092 self.dropna = dropna
   1094 if grouper is None:
-> 1095     grouper, exclusions, obj = get_grouper(
   1096         obj,
   1097         keys,
   1098         level=level,
   1099         sort=sort,
   1100         observed=observed,
   1101         dropna=self.dropna,
   1102     )
   1104 self.observed = observed
   1105 self.obj = obj

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\groupby\grouper.py:901, in get_grouper(obj, key, level, sort, observed, validate, dropna)
    899         in_axis, level, gpr = False, gpr, None
    900     else:
--> 901         raise KeyError(gpr)
    902 elif isinstance(gpr, Grouper) and gpr.key is not None:
    903     # Add key to exclusions
    904     exclusions.add(gpr.key)

KeyError: 'Category'
print([c for c in df.columns if "Category" in c])
df.groupby("Product Category")["Profit"].sum().round(0)
['Product Category', 'Product Sub-Category']
Product Category
Furniture          117433.0
Office Supplies    518021.0
Technology         886314.0
Name: Profit, dtype: float64

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)
Customer Name
Emily Phan           34005.0
Deborah Brumfield    31121.0
Grant Carroll        27977.0
Karen Carlisle       21732.0
Alejandro Grove      20589.0
Name: Profit, dtype: float64

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)
Sales Profit
Product Sub-Category
Tables 1896008.0 -99062.0
Bookcases 822652.0 -33582.0
Scissors, Rulers and Trimmers 80996.0 -7799.0
Rubber Bands 15007.0 -103.0
Storage & Organization 1070183.0 6664.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)
Product Sub-Category Sales Profit Product Category
0 Tables 1896008.0 -99062.0 Furniture
1 Bookcases 822652.0 -33582.0 Furniture
2 Scissors, Rulers and Trimmers 80996.0 -7799.0 Office Supplies
3 Rubber Bands 15007.0 -103.0 Office Supplies

Common mistake: joining two conditions with and

df[df["Profit"] < 0 and df["Discount"] > 0.08]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15904\1566104549.py in ?()
----> 1 df[df["Profit"] < 0 and df["Discount"] > 0.08]

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py in ?(self)
   1499     @final
   1500     def __bool__(self) -> NoReturn:
-> 1501         raise ValueError(
   1502             f"The truth value of a {type(self).__name__} is ambiguous. "
   1503             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1504         )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
deep = df[(df["Profit"] < 0) & (df["Discount"] > 0.08)]
print(len(deep))
print(round(deep["Profit"].sum()))
857
-208053
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)
lines loss_share avg_profit
disc_band
0-3% 3106 0.469 244.444
3-6% 2290 0.507 149.330
6-9% 2253 0.545 153.838
9%+ 750 0.560 98.616
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()
No description has been provided for this image

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)
Ship Mode
Delivery Truck    0.597
Express Air       0.454
Regular Air       0.500
Name: Profit, dtype: float64

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)
Product Category Furniture Office Supplies Technology
Customer Segment
Consumer 42728.0 88532.0 156699.0
Corporate 22008.0 203037.0 374701.0
Home Office 23979.0 121146.0 173229.0
Small Business 28717.0 105306.0 181684.0

Quick check: which segment and category pair earns the least?

cells = grid.stack()
print(cells.idxmin(), round(cells.min()))
('Corporate', 'Furniture') 22008
ship = df.groupby("Ship Mode")[["Shipping Cost", "ship_days"]]
ship.mean().round(2)
Shipping Cost ship_days
Ship Mode
Delivery Truck 45.35 2.04
Express Air 7.99 2.00
Regular Air 7.66 2.04
mix = pd.crosstab(df["Order Priority"], df["Ship Mode"],
                  normalize="index")
mix.round(2)
Ship Mode Delivery Truck Express Air Regular Air
Order Priority
Critical 0.14 0.12 0.73
High 0.14 0.12 0.74
Low 0.15 0.11 0.74
Medium 0.13 0.12 0.75
Not Specified 0.13 0.11 0.76
days = df.groupby("Order Priority")["ship_days"].median()
days.sort_values()
Order Priority
High             1.0
Medium           1.0
Not Specified    1.0
Critical         2.0
Low              4.0
Name: ship_days, dtype: float64

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)
Sales Profit sales_growth
year
2009 4209139.456 434538.73 NaN
2010 3549680.804 363871.48 -0.157
2011 3436816.702 381455.99 -0.032
2012 3719963.862 341901.78 0.082
by_year = df.pivot_table(index="year", columns="Product Category",
                         values="Profit", aggfunc="sum")
by_year.round(0)
Product Category Furniture Office Supplies Technology
year
2009 61805.0 178089.0 194645.0
2010 9402.0 117047.0 237423.0
2011 51682.0 86139.0 243635.0
2012 -5455.0 136746.0 210611.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)
year
2009      NaN
2010   -0.149
2011    0.014
2012   -0.068
Name: Sales, dtype: float64

Common mistake: resampling without a date index

df["Sales"].resample("ME").sum()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[33], line 1
----> 1 df["Sales"].resample("ME").sum()

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py:9411, in NDFrame.resample(self, rule, closed, label, convention, on, level, origin, offset, group_keys)
   9056 """
   9057 Resample time-series data.
   9058 
   (...)
   9407 Freq: 17min, dtype: int64
   9408 """
   9409 from pandas.core.resample import get_resampler
-> 9411 return get_resampler(
   9412     cast("Series | DataFrame", self),
   9413     freq=rule,
   9414     label=label,
   9415     closed=closed,
   9416     convention=convention,
   9417     key=on,
   9418     level=level,
   9419     origin=origin,
   9420     offset=offset,
   9421     group_keys=group_keys,
   9422 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\resample.py:2335, in get_resampler(obj, **kwds)
   2331 """
   2332 Create a TimeGrouper and return our resampler.
   2333 """
   2334 tg = TimeGrouper(obj, **kwds)  # type: ignore[arg-type]
-> 2335 return tg._get_resampler(obj)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\resample.py:2541, in TimeGrouper._get_resampler(self, obj)
   2533 elif isinstance(ax, TimedeltaIndex):
   2534     return TimedeltaIndexResampler(
   2535         obj,
   2536         timegrouper=self,
   2537         group_keys=self.group_keys,
   2538         gpr_index=ax,
   2539     )
-> 2541 raise TypeError(
   2542     "Only valid with DatetimeIndex, "
   2543     "TimedeltaIndex or PeriodIndex, "
   2544     f"but got an instance of '{type(ax).__name__}'"
   2545 )

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
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()))
48
2009-01-31 516303
2011-06-30 197741
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()
No description has been provided for this image

Quick check: is there a busy quarter of the year?

quarter = df["Order Date"].dt.quarter
df.groupby(quarter)["Sales"].sum().round(0)
Order Date
1    3898688.0
2    3408238.0
3    3594077.0
4    4014598.0
Name: Sales, dtype: float64

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%}")
Margin now: 10.2%
Without loss-makers: 13.7%
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
question finding
0 Profit source Technology
1 Biggest leak Tables
2 Loss lines 50.8%
3 Margin if fixed 13.7%
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)
question finding
0 Profit source Technology
1 Biggest leak Tables
2 Loss lines 50.8%
3 Margin if fixed 13.7%
loss_total = losers["Profit"].sum()
names = "; ".join(bad)
print(f"Loss-makers: {names}")
print(f"Lost in total: {loss_total:,.0f}")
Loss-makers: Tables; Bookcases; Scissors, Rulers and Trimmers; Rubber Bands
Lost in total: -140,547

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#

  1. Add a finding for the most profitable province.
  2. Which order priority has the lowest average margin?
  3. 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.