Project: Sales Analysis
In this project you'll take a small, messy sales file from a shop with branches in three counties and analyse it from start to finish: load it, clean it, explore it, summarise it by product, county and month, chart the results and write up clear conclusions. It brings together everything in this series.
The goal
The owner of a small wholesale shop wants answers to four questions about the first quarter (January to March) of 2026:
- How much revenue did we make, and what is a typical order worth?
- Which products bring in the most revenue?
- Which county performs best?
- Is revenue growing month by month?
Skills used: loading data, cleaning, descriptive statistics, grouping and Matplotlib.
Step 1: Load the data
Normally you would call pd.read_csv("sales_q1.csv"). To keep the project self-contained, the file's contents are in a string. Look carefully: the data contains some deliberate problems.
import io import pandas as pd import matplotlib.pyplot as plt csv_text = """date,product,county,units,unit_price 2026-01-08,Maize flour,Nairobi,30,180 2026-01-09,Sugar,kisumu,12,160 2026-01-15,Cooking oil,Nairobi,8,350 2026-01-20,Rice,Nakuru,15,220 2026-01-20,Rice,Nakuru,15,220 2026-02-03,Maize flour,Nakuru,25,180 2026-02-10,Sugar,Nairobi,20,160 2026-02-14,Cooking oil,Kisumu,,350 2026-02-21,Rice,Kisumu,18,220 2026-03-02,Maize flour,Kisumu,22,180 2026-03-09,Cooking oil,Nairobi ,10,350 2026-03-16,Sugar,Nakuru,14,160 2026-03-25,Maize flour,Nairobi,35,180 """ df = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"]) print(df.shape) print(df.head())
13 rows and 5 columns. Already two things stand out: units shows decimals (a sign of a missing value somewhere, since NaN forces a column to float), and rows 3 and 4 look identical.
Step 2: Inspect for problems
print(df.isna().sum())
print("Duplicate rows:", df.duplicated().sum())
print(df["county"].unique())
The inspection finds three problems:
- One missing
unitsvalue (the cooking oil sale in Kisumu on 14 February). - One duplicated row (the rice sale on 20 January was entered twice).
- Inconsistent county names:
'kisumu'in lowercase and'Nairobi 'with a trailing space. Left alone, these would create five "counties" instead of three.
Step 3: Clean the data
df = df.drop_duplicates().reset_index(drop=True)
df["county"] = df["county"].str.strip().str.title()
# Fill the missing units with the median for the SAME product
product_median = df.groupby("product")["units"].transform("median")
df["units"] = df["units"].fillna(product_median).astype(int)
print(df.shape)
print(df["county"].unique())
print("Missing values left:", df.isna().sum().sum())
Why the product median? The overall median of units is 18, which would be a strange guess for cooking oil, a product that usually sells 8 to 10 units per order. The other two cooking oil orders were 8 and 10 units, so the gap was filled with their median, 9. Once nothing is missing, astype(int) turns the column back into whole numbers. In a real report, you would mention that one value was estimated.
Because reset_index() returns a brand-new DataFrame, the column assignments that follow don't trigger a SettingWithCopyWarning. If you filter rows instead, add .copy() before changing the result.
Step 4: Add useful columns
df["revenue"] = df["units"] * df["unit_price"]
df["month"] = df["date"].dt.strftime("%Y-%m")
print(df)
The .dt accessor works on date columns like .str works on text. Formatting the month as "2026-01" (year first) means the months sort in the correct order; names such as "Feb", "Jan", "Mar" would sort alphabetically.
Step 5: Explore the overall numbers
print("Orders:", len(df))
print("Total revenue: KES", df["revenue"].sum())
print("Average order: KES", round(df["revenue"].mean(), 2))
print("Median order: KES", df["revenue"].median())
The mean is a little above the median because two large maize flour orders (5,400 and 6,300) pull it up. Both figures are worth reporting.
Step 6: Group and summarise
By product
by_product = (
df.groupby("product")
.agg(units=("units", "sum"), revenue=("revenue", "sum"))
.sort_values("revenue", ascending=False)
)
by_product["share_%"] = (by_product["revenue"] / by_product["revenue"].sum() * 100).round(1)
print(by_product)
By county
by_county = df.groupby("county")["revenue"].sum().sort_values(ascending=False)
print(by_county)
By month
monthly = df.groupby("month")["revenue"].sum()
print(monthly)
print((monthly.pct_change() * 100).round(1)) # % change from the previous month
January has no previous month, so its change is NaN. A quick sanity check: each of the three summaries adds up to the same total, KES 44,230, so no rows were lost or double-counted.
Step 7: Visualise
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
# Largest product at the top: barh draws the first item at the bottom, so reverse
bars = axes[0].barh(by_product.index[::-1], by_product["revenue"].iloc[::-1], color="tab:green")
axes[0].bar_label(bars, padding=3)
axes[0].set_title("Maize flour earns the most")
axes[0].set_xlabel("Revenue (KES)")
axes[1].plot(monthly.index, monthly.values, marker="o")
axes[1].set_title("Revenue grew every month")
axes[1].set_ylabel("Revenue (KES)")
axes[1].set_ylim(bottom=0)
fig.suptitle("Q1 2026 sales")
fig.tight_layout()
fig.savefig("q1_sales.png", dpi=150, bbox_inches="tight")
plt.show()
by_product and monthly. Both axes start at zero.What the figure shows:
| Panel | What you see |
|---|---|
| Left: horizontal bars | Maize flour's bar (20160) is more than twice as long as any other; cooking oil (9450), sugar (7360) and rice (7260) follow, each bar labelled with its value. |
| Right: line chart | Three points rising steadily from 13420 in January to 14810 in February and 16000 in March. Starting the y-axis at zero keeps the growth in honest proportion. |
Step 8: Conclusions
A short written summary is the real product of an analysis. For the shop owner:
- Overall: 12 orders brought in KES 44,230 in the quarter. A typical (median) order is worth KES 3,400.
- Products: maize flour is the star, with 45.6% of revenue and 112 units. Cooking oil is second in revenue (21.4%) despite selling the fewest units (27), because of its high unit price; it is worth keeping well stocked.
- Counties: Nairobi brings in KES 21,200, about 47.9% of revenue, ahead of Kisumu (29.4%) and Nakuru (22.7%). Cooking oil has never been sold in Nakuru, which may be an opportunity.
- Trend: revenue grew 10.4% from January to February and 8.0% from February to March.
- Limits: this is only 12 orders over three months, one missing value was estimated, and there is no cost data, so we can't speak about profit. The growth may partly reflect normal seasonal patterns, so a full year of data would make these conclusions much stronger.
Skipping the inspection step. If you had grouped the raw data, the duplicate would have added KES 3,300 of revenue that never happened, and "kisumu" and "Nairobi " would have appeared as separate counties. Always check for missing values, duplicates and inconsistent labels before you summarise.
Extend it
- Add profit: add a
unit_costcolumn, calculate profit per order and find which product has the best margin, not just the most revenue. - Day of the week: use
df["date"].dt.day_name()to find which days are busiest, then chart revenue by day in a sensible Monday-to-Sunday order. - Automate the report: turn the steps into a function that takes any CSV file, runs the cleaning and summaries, and saves the charts and a cleaned CSV (
to_csv(..., index=False)), so next quarter's report takes seconds.
Key points
- A complete analysis follows the workflow: load, inspect, clean, add features, explore, group, visualise, conclude.
- Inspection catches missing values, duplicates and inconsistent labels before they distort results.
- Fill gaps thoughtfully (here, with the median for the same product) and say that you did.
- Finish with plain-language conclusions that answer the original questions and state their limits.
Tip: use the ← and → keys to move between pages.
