This is Module 2 of the Data Analyst to Data Scientist path. In Module 1 you answered questions with SQL. Here you’ll do the same work in Python with pandas, and turn it into a script that produces a report from raw data every time you run it. That’s the step from a spreadsheet you rebuild by hand each month to an analysis you can repeat, check and extend.

You’ll build: report.py, which turns raw order data into a monthly revenue report by country, checks its own totals, and saves a CSV.

You need: Python 3 and pandas (pip install pandas).

Setup: the same shop data, as CSV files

To compare every number with Module 1, use the same data. Save this as make_data.py and run it once with python make_data.py:

# Writes the Module 1 shop data as CSV files, so both modules use the same numbers.
import csv

customers = [
    (1, "2026-01-04", "MX"), (2, "2026-01-09", "CO"), (3, "2026-01-20", "MX"), (4, "2026-02-02", "AR"),
    (5, "2026-02-11", "CO"), (6, "2026-02-25", "MX"), (7, "2026-03-03", "AR"), (8, "2026-03-15", "CO"),
    (9, "2026-03-28", "MX"),
]
orders = [
    (101, 1, "2026-01-05", 40), (102, 2, "2026-01-12", 25), (103, 3, "2026-01-22", 60),
    (104, 1, "2026-02-03", 35), (105, 4, "2026-02-04", 50), (106, 5, "2026-02-14", 20),
    (107, 2, "2026-02-20", 30), (108, 6, "2026-02-27", 45), (109, 1, "2026-03-02", 55),
    (110, 4, "2026-03-08", 40), (111, 7, "2026-03-05", 70), (112, 3, "2026-03-18", 25),
    (113, 8, "2026-03-20", 30),
]
tags = [(1, "newsletter"), (1, "referral"), (2, "newsletter"), (4, "referral"), (4, "partner")]

for name, header, rows in [
    ("customers.csv", ["customer_id", "signup_date", "country"], customers),
    ("orders.csv", ["order_id", "customer_id", "order_date", "amount"], orders),
    ("customer_tags.csv", ["customer_id", "tag"], tags),
]:
    with open(name, "w", newline="") as f:
        csv.writer(f).writerows([header, *rows])
print("wrote customers.csv, orders.csv, customer_tags.csv")

1. Load and inspect

Always look at what you loaded before you trust it: the column types, a few rows and a total you can check. Save as step1.py:

import pandas as pd

orders = pd.read_csv("orders.csv", parse_dates=["order_date"])
print(orders.dtypes)
print(orders.head(3))
print("rows:", len(orders), " revenue:", orders["amount"].sum())
order_id                int64
customer_id             int64
order_date     datetime64[us]
amount                  int64
dtype: object
   order_id  customer_id order_date  amount
0       101            1 2026-01-05      40
1       102            2 2026-01-12      25
2       103            3 2026-01-22      60
rows: 13  revenue: 525

parse_dates turns order_date into real dates, not text, which is what lets you group by month next. The revenue of 525 matches Module 1.

2. Group and aggregate

groupby with named aggregations gives one readable row per month: each output column says what it counts. Save as step2.py:

import pandas as pd

orders = pd.read_csv("orders.csv", parse_dates=["order_date"])
orders["month"] = orders["order_date"].dt.to_period("M")

monthly = orders.groupby("month").agg(
    orders=("order_id", "count"),
    buyers=("customer_id", "nunique"),
    revenue=("amount", "sum"),
)
print(monthly)
         orders  buyers  revenue
month                           
2026-01       3       3      125
2026-02       5       5      180
2026-03       5       5      220

These are exactly the numbers the CTE in Module 1 returned. When two methods agree, you can trust both.

3. Merge tables safely

Module 1 showed how a join on a key that isn’t unique silently inflates totals. pandas can check for that if you tell it what you expect. Save as step3.py:

import pandas as pd

orders = pd.read_csv("orders.csv", parse_dates=["order_date"])
customers = pd.read_csv("customers.csv")
tags = pd.read_csv("customer_tags.csv")

# Each order has exactly one customer: say so, and pandas checks it for you.
with_country = orders.merge(customers, on="customer_id", how="left", validate="many_to_one")
print("rows after merge:", len(with_country), " revenue:", with_country["amount"].sum())

# Tags are not one per customer. The same check stops the duplicate-key trap from Module 1.
try:
    orders.merge(tags, on="customer_id", how="left", validate="many_to_one")
except pd.errors.MergeError as e:
    print("MergeError:", e)
rows after merge: 13  revenue: 525
MergeError: Merge keys are not unique in right dataset; not a many-to-one merge

Duplicates in right:
  customer_id
           1
           4 ...

The first merge keeps all 13 orders and the revenue stays 525. The second fails loudly, because customers 1 and 4 have two tags each. An error you can see is much better than a dashboard that is quietly wrong. Make validate= a habit on every merge.

Project: a report that runs end to end

Now put it together. The script loads the raw files, merges in each customer’s country, pivots revenue by country and month, adds the month-over-month change, checks that the report adds up to the raw data, and saves the result. Save as report.py:

"""Monthly sales report: revenue by country and month, with month-over-month change. Run: python report.py"""
import pandas as pd

orders = pd.read_csv("orders.csv", parse_dates=["order_date"])
customers = pd.read_csv("customers.csv")

df = orders.merge(customers, on="customer_id", how="left", validate="many_to_one")
df["month"] = df["order_date"].dt.to_period("M")

by_country = df.pivot_table(index="month", columns="country", values="amount", aggfunc="sum", fill_value=0)
by_country["total"] = by_country.sum(axis=1)
by_country["change_vs_last_month"] = by_country["total"].diff()

# Check before saving: the report must add up to the raw data.
assert by_country["total"].sum() == orders["amount"].sum(), "report total does not match the orders"

by_country.to_csv("monthly_report.csv")
print(by_country)
print("saved monthly_report.csv")
country   AR  CO   MX  total  change_vs_last_month
month                                             
2026-01    0  25  100    125                   NaN
2026-02   50  50   80    180                  55.0
2026-03  110  30   80    220                  40.0
saved monthly_report.csv

The total column matches Module 1’s monthly revenue, and the assert guarantees it on every run. If someone changes the data or the code and the numbers stop adding up, the script stops before it saves a wrong report. January’s change is empty (NaN) because there is no earlier month to compare with.

Project checklist

  • All four scripts run and match the outputs above.
  • report.py also saves a second file: revenue per customer, sorted from highest to lowest.
  • You’ve rebuilt one of your own recurring reports as a script, with at least one assert that checks a total.
  • You can explain why the tags merge fails, and how you would combine tags with orders correctly.

Next: Module 3, visualisation that answers a question.

Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.