Skip to content
KALANBLON
Show contents

Chapter 6 of 7 · 25 min

Project: a cooperative's quarterly report

By the end of this chapter, you'll be able to

  • Inspect a real dataset and list its defects
  • Write a reusable cleaning function
  • Produce the requested indicators with groupby
  • Present the results in a readable form, with a text chart

Step 1: inspect

You do not clean blindly: you start by looking.

import io
import pandas as pd

csv = """date;product;region;kg;price_kg
06/01/2026;Millet;Kaolack;120;300
06/01/2026;Millet;Kaolack;120;300
14/01/2026;groundnut ;Kaolack;80;650
21/01/2026;cowpea;Thiès;45;500
03/02/2026;MILLET;Thiès;200;300
11/02/2026;Mango;Ziguinchor;?;250
18/02/2026;groundnut;Thiès;60;640
25/02/2026;fonio;Kaolack;35;900
04/03/2026;millet;Ziguinchor;90;310
12/03/2026;Groundnut;Kaolack;110;660
19/03/2026;cowpea;Thiès;70;520
26/03/2026;mango;Ziguinchor;300;240
"""
raw = pd.read_csv(io.StringIO(csv), sep=";")
print(raw.shape)
print(raw.dtypes)
print(raw["product"].unique())
print(raw.duplicated().sum(), "duplicate(s)")
(12, 5)
date        object
product     object
region      object
kg          object
price_kg     int64
dtype: object
['Millet' 'groundnut ' 'cowpea' 'MILLET' 'Mango' 'groundnut' 'fonio'
 'millet' 'Groundnut' 'mango']
1 duplicate(s)

The diagnosis:

  • the dates are text, in day/month/year format;
  • the kg column is text (object) because of the “?”;
  • the products are written in several ways (capitals, extra space);
  • one row is duplicated (the first millet sale).

Step 2: clean, analyse, present

We gather the fixes in a clean function, which returns a new table without changing the original. Then we produce the indicators, and finish with a bar chart drawn with characters: no charting library is needed for a first reading.

The results are presented simply, with a bar proportional to the turnover.

Step 4 of 4
Text description of the animation
  1. We start from the export as is, without changing it.
  2. The function fixes what it can and sets aside what is unusable: the duplicate and the sale without a weight.
  3. Three groupings answer the board's three questions.
  4. The results are presented simply, with a bar proportional to the turnover.
import io
import pandas as pd

csv = """date;product;region;kg;price_kg
06/01/2026;Millet;Kaolack;120;300
06/01/2026;Millet;Kaolack;120;300
14/01/2026;groundnut ;Kaolack;80;650
21/01/2026;cowpea;Thiès;45;500
03/02/2026;MILLET;Thiès;200;300
11/02/2026;Mango;Ziguinchor;?;250
18/02/2026;groundnut;Thiès;60;640
25/02/2026;fonio;Kaolack;35;900
04/03/2026;millet;Ziguinchor;90;310
12/03/2026;Groundnut;Kaolack;110;660
19/03/2026;cowpea;Thiès;70;520
26/03/2026;mango;Ziguinchor;300;240
"""

def clean(raw):
    df = raw.drop_duplicates().copy()
    df["date"] = pd.to_datetime(df["date"], format="%d/%m/%Y")
    df["product"] = df["product"].str.strip().str.lower()
    df["kg"] = pd.to_numeric(df["kg"], errors="coerce")
    rejected = df[df["kg"].isna()]
    if len(rejected):
        print(f"{len(rejected)} sale(s) set aside for lack of weight")
    df = df.dropna(subset=["kg"])
    df["amount"] = df["kg"] * df["price_kg"]
    return df

def bar(value, maximum, width=20):
    return "█" * round(value / maximum * width)

sales = clean(pd.read_csv(io.StringIO(csv), sep=";"))
print(len(sales), "usable sales")

by_month = sales.groupby(sales["date"].dt.to_period("M"))["amount"].sum()
print("\nTurnover by month (FCFA)")
for month, total in by_month.items():
    print(f"{month}  {total:>9,.0f}  {bar(total, by_month.max())}")

by_product = sales.groupby("product")["amount"].sum().sort_values(ascending=False)
print("\nTop 3 products")
print(by_product.head(3))

by_region = sales.groupby("region").agg(sales=("amount", "count"), turnover=("amount", "sum"))
print("\nBy region")
print(by_region.sort_values("turnover", ascending=False))
1 sale(s) set aside for lack of weight
10 usable sales

Turnover by month (FCFA)
2026-01    110,500  ███████████
2026-02    129,900  ████████████
2026-03    208,900  ████████████████████

Top 3 products
product
groundnut    163000.0
millet       123900.0
mango         72000.0
Name: amount, dtype: float64

By region
            sales  turnover
region                     
Kaolack         4  192100.0
Thiès           4  157300.0
Ziguinchor      2   99900.0

A few details:

  • .copy() creates a real new table: you can change it without touching raw, and pandas does not worry about an ambiguous change;
  • dropna(subset=["kg"]) only removes the rows where the weight is missing;
  • {total:>9,.0f} right-aligns the number on 9 characters, with a comma between thousands and no decimals;
  • each bar's length is proportional to the biggest month, which gets 20.

Mini-lab: your own reportPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the weighted average price

The board also wants the average price per kilo of each product over the quarter. Careful: a 300 kg sale must count more than a 35 kg sale. Compute this average price weighted by quantities for mango, groundnut and millet, rounded to the nearest integer.

# Cleaned data: product, kg, price_kg
sales = pd.DataFrame({
    "product": ["millet", "groundnut", "millet", "groundnut", "millet", "groundnut", "mango"],
    "kg": [120, 80, 200, 60, 90, 110, 300],
    "price_kg": [300, 650, 300, 640, 310, 660, 240],
})
Hint 1
The weighted average price is the total turnover divided by the total weight: Σ(kg × price) / Σ kg.
Hint 2
Compute amount, group by product summing amount and kg, then divide one column by the other.
Show the solution and common mistakes
import pandas as pd

sales = pd.DataFrame({
    "product": ["millet", "groundnut", "millet", "groundnut", "millet", "groundnut", "mango"],
    "kg": [120, 80, 200, 60, 90, 110, 300],
    "price_kg": [300, 650, 300, 640, 310, 660, 240],
})
sales["amount"] = sales["kg"] * sales["price_kg"]
totals = sales.groupby("product")[["amount", "kg"]].sum()
totals["avg_price"] = (totals["amount"] / totals["kg"]).round()
print(totals)
print(sales.groupby("product")["price_kg"].mean().round(1))
           amount   kg  avg_price
product                          
groundnut  163000  250      652.0
mango       72000  300      240.0
millet     123900  410      302.0
product
groundnut    650.0
mango        240.0
millet       303.3
Name: price_kg, dtype: float64

The simple mean of the prices (second table) treats every sale equally. For millet, it gives 303.3, against 302 for the weighted average: the 310 FCFA sale was only 90 kg, out of 410 kg sold.

Common mistakes:

  • Using groupby("product")["price_kg"].mean(): that is the simple mean, which gives too much weight to small sales.
  • Adding up prices per kilo: a sum of prices makes no sense. You add up amounts and weights, then divide.

Summary

  1. 1Inspect before cleaning: shape, dtypes, unique and duplicated reveal the defects.
  2. 2A cleaning function works on a copy and reports what it sets aside.
  3. 3Three groupings (month, product, region) are often enough to answer a board's questions.
  4. 4An average price is computed by weighting with quantities: Σ amounts / Σ quantities.
  5. 5The raw data stays intact, so that the analysis can be rerun from scratch.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.