Skip to content
Kuza Ndoto Academy

Project: Sales Analysis

Beginner → IntermediateChapter 6 · Page 19 of 207 min readUpdated 15 Nov 2026

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:

  1. How much revenue did we make, and what is a typical order worth?
  2. Which products bring in the most revenue?
  3. Which county performs best?
  4. 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, 5) date product county units unit_price 0 2026-01-08 Maize flour Nairobi 30.0 180 1 2026-01-09 Sugar kisumu 12.0 160 2 2026-01-15 Cooking oil Nairobi 8.0 350 3 2026-01-20 Rice Nakuru 15.0 220 4 2026-01-20 Rice Nakuru 15.0 220

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())
date 0 product 0 county 0 units 1 unit_price 0 dtype: int64 Duplicate rows: 1 ['Nairobi' 'kisumu' 'Nakuru' 'Kisumu' 'Nairobi ']

The inspection finds three problems:

  • One missing units value (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())
(12, 5) ['Nairobi' 'Kisumu' 'Nakuru'] Missing values left: 0

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.

Note

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)
date product county units unit_price revenue month 0 2026-01-08 Maize flour Nairobi 30 180 5400 2026-01 1 2026-01-09 Sugar Kisumu 12 160 1920 2026-01 2 2026-01-15 Cooking oil Nairobi 8 350 2800 2026-01 3 2026-01-20 Rice Nakuru 15 220 3300 2026-01 4 2026-02-03 Maize flour Nakuru 25 180 4500 2026-02 5 2026-02-10 Sugar Nairobi 20 160 3200 2026-02 6 2026-02-14 Cooking oil Kisumu 9 350 3150 2026-02 7 2026-02-21 Rice Kisumu 18 220 3960 2026-02 8 2026-03-02 Maize flour Kisumu 22 180 3960 2026-03 9 2026-03-09 Cooking oil Nairobi 10 350 3500 2026-03 10 2026-03-16 Sugar Nakuru 14 160 2240 2026-03 11 2026-03-25 Maize flour Nairobi 35 180 6300 2026-03

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())
Orders: 12 Total revenue: KES 44230 Average order: KES 3685.83 Median order: KES 3400.0

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)
units revenue share_% product Maize flour 112 20160 45.6 Cooking oil 27 9450 21.4 Sugar 46 7360 16.6 Rice 33 7260 16.4

By county

by_county = df.groupby("county")["revenue"].sum().sort_values(ascending=False)
print(by_county)
county Nairobi 21200 Kisumu 12990 Nakuru 10040 Name: revenue, dtype: int64

By month

monthly = df.groupby("month")["revenue"].sum()
print(monthly)
print((monthly.pct_change() * 100).round(1))   # % change from the previous month
month 2026-01 13420 2026-02 14810 2026-03 16000 Name: revenue, dtype: int64 month 2026-01 NaN 2026-02 10.4 2026-03 8.0 Name: revenue, dtype: float64

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()
Maize flour earns the most Maize flour Cooking oil Sugar Rice 20160 9450 7360 7260 0 10,000 20,000 Revenue grew every month 0 5,000 10,000 15,000 20,000 13420 14810 16000 2026-01 2026-02 2026-03
Figure 1. Preview of the two panels, drawn from by_product and monthly. Both axes start at zero.

What the figure shows:

PanelWhat you see
Left: horizontal barsMaize 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 chartThree 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.
Common mistake

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

  1. Add profit: add a unit_cost column, calculate profit per order and find which product has the best margin, not just the most revenue.
  2. 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.
  3. 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.
Up next · ProjectsData Science QuizTest yourself across the series.
→

Tip: use the ← and → keys to move between pages.