Pandas Mini Project
In this project you'll analyse one week of sales from a small café called Bean There, the way a data analyst would: load the raw export, clean it, enrich it with a product catalogue, answer business questions and finish with charts and a short report. It brings together most of the course: read_csv, cleaning, merge, groupby, pivot_table, dates, rolling, method chaining and plotting.
The owner wants to know:
- How much revenue and profit did the week bring in?
- Which products and categories sell best?
- Which days are busiest, and is business growing during the week?
Every step below is a complete program you can run and modify. Each one starts by loading the same raw data, because the playgrounds don't share variables.
Step 1: Load and inspect the raw data
The till exports a CSV file. In real life you'd call pd.read_csv("sales_week19.csv"); here the text is inline.
import io
import pandas as pd
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
raw = pd.read_csv(io.StringIO(RAW))
print(raw.head())
raw.info()
print("duplicated rows:", raw.duplicated().sum())
print(raw["product"].unique())
print(raw["qty"].describe()) order_id date product qty unit_price
0 1001 2024-05-06 Latte 2.0 $3.80
1 1002 2024-05-06 espresso 1.0 $2.50
2 1003 2024-05-06 Croissant 3.0 $2.90
3 1004 2024-05-07 Latte 1.0 $3.80
4 1005 2024-05-07 Cappuccino 2.0 $3.60
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 24 entries, 0 to 23
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 order_id 24 non-null int64
1 date 24 non-null object
2 product 24 non-null object
3 qty 23 non-null float64
4 unit_price 24 non-null object
dtypes: float64(1), int64(1), object(3)
memory usage: 744.0+ bytes
duplicated rows: 1
['Latte' 'espresso ' 'Croissant' 'Cappuccino' 'Muffin' 'latte' 'Espresso'
'Cold Brew']
count 23.000000
mean 4.086957
std 7.890806
min 1.000000
25% 2.000000
50% 2.000000
75% 3.000000
max 40.000000
Name: qty, dtype: float64
The quick inspection already shows every problem we need to fix:
dateandunit_priceare text (object); the prices carry a$sign.qtyhas 23 non-null values for 24 rows, so one quantity is missing; that gap is also why the column isfloat64.- Order 1005 appears twice.
- Product names are inconsistent:
espresso(lower case with a trailing space) andlatte. - The maximum quantity is 40, far above everything else: a typo at the till.
Step 2: Clean the data
We put all cleaning steps into one function, written as a method chain. The café manager confirmed order 1019 was 4 lattes, and the order with the missing quantity was a single muffin.
import io
import pandas as pd
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
def clean(df):
df = (
df
.drop_duplicates()
.assign(
date=lambda d: pd.to_datetime(d["date"]),
product=lambda d: d["product"].str.strip().str.title(),
unit_price=lambda d: d["unit_price"].str.replace("quot;, "", regex=False).astype(float),
qty=lambda d: d["qty"].fillna(1),
)
)
df.loc[df["order_id"] == 1019, "qty"] = 4 # confirmed typo
return df.astype({"qty": "int64"}).reset_index(drop=True)
sales = clean(pd.read_csv(io.StringIO(RAW)))
print(sales.dtypes)
print(sales["product"].value_counts())
print(len(sales), "orders, max qty", sales["qty"].max())order_id int64
date datetime64[ns]
product object
qty int64
unit_price float64
dtype: object
product
Latte 7
Croissant 4
Espresso 3
Cappuccino 3
Muffin 3
Cold Brew 3
Name: count, dtype: int64
23 orders, max qty 5
Now every column has the right type, product names are consistent, and the 23 unique orders remain.
Step 3: Enrich with the product catalogue
Revenue tells only half the story; the owner also cares about profit. The catalogue lists each product's category and what one unit costs the café to make. A left merge attaches it to every order, and validate guards against duplicate catalogue rows.
import io
import pandas as pd
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
CATALOGUE = pd.DataFrame({
"product": ["Espresso", "Latte", "Cappuccino", "Cold Brew", "Croissant", "Muffin"],
"category": ["coffee", "coffee", "coffee", "coffee", "bakery", "bakery"],
"unit_cost": [0.60, 1.10, 1.00, 1.40, 1.20, 1.30],
})
def clean(df):
df = (df.drop_duplicates()
.assign(date=lambda d: pd.to_datetime(d["date"]),
product=lambda d: d["product"].str.strip().str.title(),
unit_price=lambda d: d["unit_price"].str.replace("quot;, "", regex=False).astype(float),
qty=lambda d: d["qty"].fillna(1)))
df.loc[df["order_id"] == 1019, "qty"] = 4
return df.astype({"qty": "int64"}).reset_index(drop=True)
def enrich(df):
return (df.merge(CATALOGUE, on="product", how="left", validate="many_to_one")
.assign(revenue=lambda d: d["qty"] * d["unit_price"],
profit=lambda d: d["qty"] * (d["unit_price"] - d["unit_cost"]),
weekday=lambda d: d["date"].dt.day_name()))
sales = enrich(clean(pd.read_csv(io.StringIO(RAW))))
print(sales[["order_id", "product", "category", "qty", "revenue", "profit", "weekday"]].head(6))
print("unmatched products:", sales["category"].isna().sum())
print(f"Week revenue: ${sales['revenue'].sum():.2f}, profit: ${sales['profit'].sum():.2f}") order_id product category qty revenue profit weekday
0 1001 Latte coffee 2 7.6 5.4 Monday
1 1002 Espresso coffee 1 2.5 1.9 Monday
2 1003 Croissant bakery 3 8.7 5.1 Monday
3 1004 Latte coffee 1 3.8 2.7 Tuesday
4 1005 Cappuccino coffee 2 7.2 5.2 Tuesday
5 1006 Muffin bakery 1 3.2 1.9 Tuesday
unmatched products: 0
Week revenue: $195.80, profit: $131.40
Checking for unmatched products (a NaN category) after the merge is a cheap safety net: a new product missing from the catalogue would show up here.
Step 4: Products and categories
Now the business questions. Named aggregation gives a clean report table per product, and margin shows how much of each euro of revenue is profit.
import io
import pandas as pd
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
CATALOGUE = pd.DataFrame({
"product": ["Espresso", "Latte", "Cappuccino", "Cold Brew", "Croissant", "Muffin"],
"category": ["coffee", "coffee", "coffee", "coffee", "bakery", "bakery"],
"unit_cost": [0.60, 1.10, 1.00, 1.40, 1.20, 1.30],
})
def clean(df):
df = (df.drop_duplicates()
.assign(date=lambda d: pd.to_datetime(d["date"]),
product=lambda d: d["product"].str.strip().str.title(),
unit_price=lambda d: d["unit_price"].str.replace("quot;, "", regex=False).astype(float),
qty=lambda d: d["qty"].fillna(1)))
df.loc[df["order_id"] == 1019, "qty"] = 4
return df.astype({"qty": "int64"}).reset_index(drop=True)
def enrich(df):
return (df.merge(CATALOGUE, on="product", how="left", validate="many_to_one")
.assign(revenue=lambda d: d["qty"] * d["unit_price"],
profit=lambda d: d["qty"] * (d["unit_price"] - d["unit_cost"]),
weekday=lambda d: d["date"].dt.day_name()))
sales = enrich(clean(pd.read_csv(io.StringIO(RAW))))
by_product = (sales.groupby("product")
.agg(units=("qty", "sum"), revenue=("revenue", "sum"), profit=("profit", "sum"))
.assign(margin=lambda d: d["profit"] / d["revenue"])
.sort_values("revenue", ascending=False)
.round(2))
print(by_product)
by_category = sales.groupby("category")[["revenue", "profit"]].sum()
by_category["share"] = (by_category["revenue"] / by_category["revenue"].sum()).round(3)
print(by_category) units revenue profit margin
product
Latte 19 72.2 51.3 0.71
Croissant 13 37.7 22.1 0.59
Cold Brew 7 29.4 19.6 0.67
Muffin 7 22.4 13.3 0.59
Cappuccino 6 21.6 15.6 0.72
Espresso 5 12.5 9.5 0.76
revenue profit share
category
bakery 60.1 35.4 0.307
coffee 135.7 96.0 0.693
Lattes are the top earner, and coffee brings in most of the revenue. Bakery items have noticeably lower margins than coffee: useful input for the next price review.
Step 5: Days of the week and the trend
A pivot table shows units per weekday and category; a daily revenue series with a 3-day rolling average shows the trend through the week.
import io
import pandas as pd
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
CATALOGUE = pd.DataFrame({
"product": ["Espresso", "Latte", "Cappuccino", "Cold Brew", "Croissant", "Muffin"],
"category": ["coffee", "coffee", "coffee", "coffee", "bakery", "bakery"],
"unit_cost": [0.60, 1.10, 1.00, 1.40, 1.20, 1.30],
})
def clean(df):
df = (df.drop_duplicates()
.assign(date=lambda d: pd.to_datetime(d["date"]),
product=lambda d: d["product"].str.strip().str.title(),
unit_price=lambda d: d["unit_price"].str.replace("quot;, "", regex=False).astype(float),
qty=lambda d: d["qty"].fillna(1)))
df.loc[df["order_id"] == 1019, "qty"] = 4
return df.astype({"qty": "int64"}).reset_index(drop=True)
def enrich(df):
return (df.merge(CATALOGUE, on="product", how="left", validate="many_to_one")
.assign(revenue=lambda d: d["qty"] * d["unit_price"],
profit=lambda d: d["qty"] * (d["unit_price"] - d["unit_cost"]),
weekday=lambda d: d["date"].dt.day_name()))
sales = enrich(clean(pd.read_csv(io.StringIO(RAW))))
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
sales["weekday"] = pd.Categorical(sales["weekday"], categories=days, ordered=True)
units = sales.pivot_table(index="weekday", columns="category", values="qty",
aggfunc="sum", fill_value=0, observed=True, margins=True)
print(units)
daily = sales.set_index("date")["revenue"].resample("D").sum()
trend = pd.DataFrame({
"revenue": daily,
"avg_3d": daily.rolling(3).mean().round(2),
"vs_prev_day": daily.pct_change().mul(100).round(1),
})
print(trend)
print("Busiest day:", daily.idxmax().day_name())category bakery coffee All
weekday
Monday 3 3 6
Tuesday 1 3 4
Wednesday 2 5 7
Thursday 2 3 5
Friday 5 6 11
Saturday 4 10 14
Sunday 3 7 10
All 20 37 57
revenue avg_3d vs_prev_day
date
2024-05-06 18.8 NaN NaN
2024-05-07 14.2 NaN -24.5
2024-05-08 22.2 18.40 56.3
2024-05-09 17.6 18.00 -20.7
2024-05-10 38.1 25.97 116.5
2024-05-11 51.4 35.70 34.9
2024-05-12 33.5 41.00 -34.8
Busiest day: Saturday
Making weekday an ordered categorical keeps Monday…Sunday in calendar order instead of alphabetical. The rolling average climbs steadily from midweek, and Friday and Saturday are clearly the busiest days, selling more than twice as much as Tuesday.
Step 6: Charts
Two charts for the owner: revenue per product (bars, split into profit and cost) and daily revenue with its trend line.
import io
import pandas as pd
import matplotlib.pyplot as plt
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
CATALOGUE = pd.DataFrame({
"product": ["Espresso", "Latte", "Cappuccino", "Cold Brew", "Croissant", "Muffin"],
"category": ["coffee", "coffee", "coffee", "coffee", "bakery", "bakery"],
"unit_cost": [0.60, 1.10, 1.00, 1.40, 1.20, 1.30],
})
def clean(df):
df = (df.drop_duplicates()
.assign(date=lambda d: pd.to_datetime(d["date"]),
product=lambda d: d["product"].str.strip().str.title(),
unit_price=lambda d: d["unit_price"].str.replace("quot;, "", regex=False).astype(float),
qty=lambda d: d["qty"].fillna(1)))
df.loc[df["order_id"] == 1019, "qty"] = 4
return df.astype({"qty": "int64"}).reset_index(drop=True)
def enrich(df):
return (df.merge(CATALOGUE, on="product", how="left", validate="many_to_one")
.assign(revenue=lambda d: d["qty"] * d["unit_price"],
profit=lambda d: d["qty"] * (d["unit_price"] - d["unit_cost"]),
weekday=lambda d: d["date"].dt.day_name()))
sales = enrich(clean(pd.read_csv(io.StringIO(RAW))))
per_product = (sales.groupby("product")[["revenue", "profit"]].sum()
.assign(cost=lambda d: d["revenue"] - d["profit"])
.sort_values("revenue"))
daily = sales.set_index("date")["revenue"].resample("D").sum()
daily.index = daily.index.strftime("%a %d")
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
per_product[["profit", "cost"]].plot(kind="barh", stacked=True, ax=axes[0],
color=["tab:green", "tab:gray"],
title="Revenue per product ($)")
daily.plot(ax=axes[1], marker="o", label="daily revenue", title="Revenue per day ($)")
daily.rolling(3).mean().plot(ax=axes[1], linestyle="--", label="3-day average")
axes[1].legend()
fig.tight_layout()
plt.show()
print("Charts: revenue split per product, and daily revenue with a 3-day average")Charts: revenue split per product, and daily revenue with a 3-day average
A stacked horizontal bar shows both the total length (revenue) and how much of it is profit.
Step 7: The weekly report
Finally, wrap the analysis in a function that prints a short plain-text report. Next week, the owner runs the same script on the new export and gets a fresh report in a second.
import io
import pandas as pd
RAW = """order_id,date,product,qty,unit_price
1001,2024-05-06,Latte,2,$3.80
1002,2024-05-06,espresso ,1,$2.50
1003,2024-05-06,Croissant,3,$2.90
1004,2024-05-07,Latte,1,$3.80
1005,2024-05-07,Cappuccino,2,$3.60
1005,2024-05-07,Cappuccino,2,$3.60
1006,2024-05-07,Muffin,,$3.20
1007,2024-05-08,latte,3,$3.80
1008,2024-05-08,Croissant,2,$2.90
1009,2024-05-08,Espresso,2,$2.50
1010,2024-05-09,Cappuccino,1,$3.60
1011,2024-05-09,Muffin,2,$3.20
1012,2024-05-09,Latte,2,$3.80
1013,2024-05-10,Latte,4,$3.80
1014,2024-05-10,Croissant,5,$2.90
1015,2024-05-10,Cold Brew,2,$4.20
1016,2024-05-11,Cold Brew,3,$4.20
1017,2024-05-11,Cappuccino,3,$3.60
1018,2024-05-11,Muffin,4,$3.20
1019,2024-05-11,Latte,40,$3.80
1020,2024-05-12,Espresso,2,$2.50
1021,2024-05-12,Croissant,3,$2.90
1022,2024-05-12,Cold Brew,2,$4.20
1023,2024-05-12,Latte,3,$3.80
"""
CATALOGUE = pd.DataFrame({
"product": ["Espresso", "Latte", "Cappuccino", "Cold Brew", "Croissant", "Muffin"],
"category": ["coffee", "coffee", "coffee", "coffee", "bakery", "bakery"],
"unit_cost": [0.60, 1.10, 1.00, 1.40, 1.20, 1.30],
})
def clean(df):
df = (df.drop_duplicates()
.assign(date=lambda d: pd.to_datetime(d["date"]),
product=lambda d: d["product"].str.strip().str.title(),
unit_price=lambda d: d["unit_price"].str.replace("quot;, "", regex=False).astype(float),
qty=lambda d: d["qty"].fillna(1)))
df.loc[df["order_id"] == 1019, "qty"] = 4
return df.astype({"qty": "int64"}).reset_index(drop=True)
def enrich(df):
return (df.merge(CATALOGUE, on="product", how="left", validate="many_to_one")
.assign(revenue=lambda d: d["qty"] * d["unit_price"],
profit=lambda d: d["qty"] * (d["unit_price"] - d["unit_cost"]),
weekday=lambda d: d["date"].dt.day_name()))
def weekly_report(sales):
start, end = sales["date"].min(), sales["date"].max()
revenue, profit = sales["revenue"].sum(), sales["profit"].sum()
top = sales.groupby("product")["revenue"].sum().nlargest(3)
daily = sales.groupby("weekday")["revenue"].sum()
lines = [
f"BEAN THERE - weekly report {start:%d %b} to {end:%d %b %Y}",
"-" * 52,
f"Orders : {len(sales)} Items sold: {sales['qty'].sum()}",
f"Revenue : ${revenue:8.2f}",
f"Profit : ${profit:8.2f} ({profit / revenue:.0%} margin)",
f"Avg order: ${sales['revenue'].mean():.2f}",
"Top products:",
]
lines += [f" {i}. {name:<10} ${value:6.2f}" for i, (name, value) in enumerate(top.items(), 1)]
lines.append(f"Best day: {daily.idxmax()} (${daily.max():.2f}), "
f"quietest: {daily.idxmin()} (${daily.min():.2f})")
return "\n".join(lines)
sales = enrich(clean(pd.read_csv(io.StringIO(RAW))))
print(weekly_report(sales))BEAN THERE - weekly report 06 May to 12 May 2024
----------------------------------------------------
Orders : 23 Items sold: 57
Revenue : $ 195.80
Profit : $ 131.40 (67% margin)
Avg order: $8.51
Top products:
1. Latte $ 72.20
2. Croissant $ 37.70
3. Cold Brew $ 29.40
Best day: Saturday ($51.40), quietest: Tuesday ($14.20)
Ideas to extend the project
- More weeks: concatenate several weekly exports with
pd.concat(..., keys=[...])and compare weeks withpct_change(). - Hours: add an order time column and find the rush hour with
.dt.hourandvalue_counts(). - Basket analysis: group by a receipt id to see which products are bought together.
- Export: save the product table with
to_csv("products.csv")or the report text to a file.
Test yourself
Why does the project check sales["category"].isna().sum() after the merge?
- To count the coffee orders
- To catch products that are missing from the catalogue
- To remove duplicate rows
- Because merge always creates NaN
Why was weekday converted to an ordered categorical before pivoting?
- To save memory
- So the days appear in calendar order instead of alphabetical order
- Because pivot_table requires categories
- To remove missing days
What does validate="many_to_one" protect against in the merge?
- Orders without a date
- Duplicate products in the catalogue multiplying order rows
- Negative prices
- Missing quantities