Data analysis with pandas · Lesson 15 of 15
Project: analyse a shop's sales
Put the whole course together: load a messy sales file, check it, clean it, add totals, summarise by product and day and finish with a chart.
Time to use everything from this course on one small, realistic job. A café owner sends you a week of sales in shop.csv and asks three questions: what were the total sales, which product earns the most, and which day was busiest? Like most real files, this one has a few problems.
Step 1: load and look
Always start by printing the data, its shape and its types, as in Reading a CSV file and a first look. Look for anything odd before you calculate.
import pandas as pd
df = pd.read_csv("shop.csv")
print(df)
print(df.shape)
print(df.dtypes)date product qty price 0 2026-04-06 coffee 12.0 €2.50 1 2026-04-06 cake 4.0 €3.80 2 2026-04-07 coffee 9.0 €2.50 3 2026-04-07 Tea 5.0 €2.00 4 2026-04-08 coffee 15.0 €2.50 5 2026-04-08 cake NaN €3.80 6 2026-04-09 tea 7.0 €2.00 7 2026-04-09 coffee 11.0 €2.50 8 2026-04-10 cake 8.0 €3.80 9 2026-04-10 COFFEE 18.0 €2.50 10 2026-04-10 coffee 18.0 €2.50 (11, 4) date object product object qty float64 price object dtype: object
Four problems show up: product names with spaces and capitals ( Tea , COFFEE), prices stored as text with a € sign (so price is object), a missing quantity (NaN, which also made qty a decimal column) and the last row printed twice once the names are cleaned.
Step 2: clean
Fix each problem with the tools from Missing data: isna, fillna, dropna and Cleaning text and types. The order matters: clean the names before removing duplicates, otherwise COFFEE and coffee look different.
import pandas as pd
df = pd.read_csv("shop.csv")
df["product"] = df["product"].str.strip().str.lower()
df["price"] = df["price"].str.replace("€", "", regex=False).astype(float)
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
before = len(df)
df = df.drop_duplicates()
print("Duplicates removed:", before - len(df))
print("Missing qty:", int(df["qty"].isna().sum()))
df["qty"] = df["qty"].fillna(0).astype("int64")
print(df.dtypes)Duplicates removed: 1 Missing qty: 1 date datetime64[ns] product object qty int64 price float64 dtype: object
The missing cake quantity is set to 0: the owner confirmed nothing was sold that time.
Step 3: totals
import pandas as pd
df = pd.read_csv("shop.csv")
df["product"] = df["product"].str.strip().str.lower()
df["price"] = df["price"].str.replace("€", "", regex=False).astype(float)
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
df = df.drop_duplicates()
df["qty"] = df["qty"].fillna(0).astype("int64")
df["total"] = df["qty"] * df["price"]
print(df[["date", "product", "qty", "total"]].tail(4))
print(f"Total sales: {df['total'].sum():.2f} €")
print("Items sold:", df["qty"].sum())date product qty total 6 2026-04-09 tea 7 14.0 7 2026-04-09 coffee 11 27.5 8 2026-04-10 cake 8 30.4 9 2026-04-10 coffee 18 45.0 Total sales: 232.10 € Items sold: 89
The cleaning steps from step 2 come first; then a total column (quantity × price) answers the first question.
Step 4: by product and by day
groupby answers the other two questions. Named aggregation gives clear column names, and sort_values puts the best first.
import pandas as pd
df = pd.read_csv("shop.csv")
df["product"] = df["product"].str.strip().str.lower()
df["price"] = df["price"].str.replace("€", "", regex=False).astype(float)
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
df = df.drop_duplicates()
df["qty"] = df["qty"].fillna(0).astype("int64")
df["total"] = df["qty"] * df["price"]
by_product = df.groupby("product").agg(
items=("qty", "sum"),
sales=("total", "sum"),
).sort_values("sales", ascending=False)
print(by_product)
print("Top product:", by_product.index[0])
by_day = df.groupby(df["date"].dt.day_name(), sort=False)["total"].sum()
print(by_day)
print("Busiest day:", by_day.idxmax())items sales product coffee 65 162.5 cake 12 45.6 tea 12 24.0 Top product: coffee date Monday 45.2 Tuesday 32.5 Wednesday 37.5 Thursday 41.5 Friday 75.4 Name: total, dtype: float64 Busiest day: Friday
sort=False keeps the days in the order they appear in the file instead of A to Z.
Step 5: the chart
import pandas as pd
df = pd.read_csv("shop.csv")
df["product"] = df["product"].str.strip().str.lower()
df["price"] = df["price"].str.replace("€", "", regex=False).astype(float)
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
df = df.drop_duplicates()
df["qty"] = df["qty"].fillna(0).astype("int64")
df["total"] = df["qty"] * df["price"]
import matplotlib.pyplot as plt
share = (df.groupby("product")["total"].sum() / df["total"].sum() * 100).round()
print(share.astype("int64").to_dict())
by_day = df.groupby(df["date"].dt.day_name(), sort=False)["total"].sum()
by_day.plot(kind="bar", color="teal", title="Café sales per day (€)")
plt.xticks(rotation=0)
plt.ylabel("€")
plt.tight_layout()
plt.show(){'cake': 20, 'coffee': 70, 'tea': 10}
Each product's share of the week in whole percents, then a bar chart of sales per day: the picture the owner will remember.
by_product.to_csv("summary.csv") or to_excel, so the owner gets a file as well as a chart.✎ Exercise
Using the cleaned data, make a pivot table with product down the side, the weekday across the top (use df["day"] = df["date"].dt.strftime("%a")), the sum of qty in the cells and 0 for gaps. Print it with the columns in the order Mon, Tue, Wed, Thu, Fri.
Hint: Add the day column, then pivot_table(index="product", columns="day", values="qty", aggfunc="sum", fill_value=0).
import pandas as pd
df = pd.read_csv("shop.csv")
df["product"] = df["product"].str.strip().str.lower()
df["price"] = df["price"].str.replace("€", "", regex=False).astype(float)
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
df = df.drop_duplicates()
df["qty"] = df["qty"].fillna(0).astype("int64")
df["total"] = df["qty"] * df["price"]
# your code here
Expected output:
day Mon Tue Wed Thu Fri product cake 4 0 0 0 8 coffee 12 9 15 11 18 tea 0 5 0 7 0
Show a solution
import pandas as pd
df = pd.read_csv("shop.csv")
df["product"] = df["product"].str.strip().str.lower()
df["price"] = df["price"].str.replace("€", "", regex=False).astype(float)
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d")
df = df.drop_duplicates()
df["qty"] = df["qty"].fillna(0).astype("int64")
df["total"] = df["qty"] * df["price"]
df["day"] = df["date"].dt.strftime("%a")
grid = df.pivot_table(index="product", columns="day", values="qty",
aggfunc="sum", fill_value=0)
print(grid[["Mon", "Tue", "Wed", "Thu", "Fri"]])day Mon Tue Wed Thu Fri product cake 4 0 0 0 8 coffee 12 9 15 11 18 tea 0 5 0 7 0
Check yourself
1. Why clean the product names before drop_duplicates()?
Duplicates must match exactly; after strip() and lower() the two rows are identical.
2. Why was qty a decimal column when the file was loaded?
NaN is a float value; a whole-number column with a gap is stored as float64 until you fill it and convert with astype("int64").
3. Which line gives the total sales per product?
Group by product, take the total column, add it up per group.