Project: analysing reviews with AI
Put it all together. You'll build a small but genuinely useful AI data pipeline — the kind analysts build every day.
Learning objectives
- Combine pandas and an AI API in one workflow
- Test AI processing on a sample before scaling
- Check AI labels for errors
- Summarise results and generate a brief
- Apply good habits: environments, scripts, Git, code review and data protection
- Reorganise notebook cells into functions and a main()
- Write results to files and add a check that fails loudly
6.1 The project: analyse customer reviews with AI
You'll combine everything: a DataFrame of reviews, a function that asks an AI model to classify each one, and pandas to summarise the results into insights a manager can act on.
As in Module 5, the cells here talk to a small pretend model built into the page, so you can run the whole project without an API key. The labels it gives are simple and rule-based. To run the project with a real model, copy the code into Colab and add your own key.
6.2 Step 1 — set up and load the data
First, the helper functions from Module 5:
import anthropic
from typing import Literal
from pydantic import BaseModel
client = anthropic.Anthropic()
MODEL = "YOUR-MODEL-NAME"
def ask(prompt, max_tokens=500):
r = client.messages.create(model=MODEL, max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}])
return r.content[0].text
class Review(BaseModel):
sentiment: Literal["positive", "neutral", "negative"]
topic: Literal["product", "delivery", "price", "other"]
summary: str
def classify_review(text):
r = client.messages.parse(
model=MODEL, max_tokens=200, output_format=Review,
messages=[{"role": "user", "content": f"Classify this customer review.\n\nReview: {text}"}])
return r.parsed_output.model_dump()
Then the data:
import pandas as pd
pd.set_option("display.max_colwidth", 48) # show more of each review when printing
reviews = pd.DataFrame({
"id": range(1, 9),
"text": [
"Gorgeous board, really solid. Arrived in two days.",
"Took nearly three weeks to arrive and no tracking updates.",
"Good quality but a bit expensive for the size.",
"The handle on the spatula snapped after a week.",
"Perfect gift, beautifully packaged!",
"Courier left it in the rain, box soaked.",
"Fine. Does the job.",
"Customer service sorted my refund quickly, thank you.",
],
})
print(reviews)
6.3 Step 2 — classify with AI (test small first)
sample = reviews.head(3).copy()
sample["result"] = sample["text"].apply(classify_review)
print(sample)
Looks good? Then run it on everything:
results = reviews["text"].apply(classify_review).tolist() # one dictionary per review
labelled = pd.concat([reviews, pd.json_normalize(results)], axis=1) # dictionaries -> columns
print(labelled)
6.4 Step 3 — check the AI's work
Never trust AI labels blindly (see Validating AI Output). A schema guarantees the shape of the answer, not the judgement behind it. Read a sample against the original text, count any gaps, and fix the prompt if needed. Do you agree with every label below?
print(labelled[["text", "sentiment", "topic"]])
print("Missing labels:", labelled["sentiment"].isna().sum())
print(labelled["topic"].value_counts())
6.5 Step 4 — summarise for a manager
table = pd.crosstab(labelled["topic"], labelled["sentiment"])
print(table)
negatives = labelled[labelled["sentiment"] == "negative"]["text"].tolist()
brief = ask("Write a 4-bullet summary for a shop manager of these negative reviews, "
"with one suggested action each:\n- " + "\n- ".join(negatives))
print(brief)
6.6 Good habits as you grow
- Virtual environments keep each project's packages separate:
python -m venv .venv, or the newer and much fasteruvtool (uv venv,uv add pandas), which many new projects now use - requirements.txt (or
pyproject.tomlwith uv) records the packages your project needs - Move from notebooks to scripts (
.pyfiles) for code you'll reuse - Version control with Git — but add secrets files to
.gitignore - Small functions with clear names; test them on known inputs
- Review AI-written code before you run it, just as you'd check a colleague's
- Data protection — don't send personal data to APIs without a lawful basis and an approved provider
6.7 Where next?
You now have the Python foundations used throughout the technical courses. Next steps: Data Quality & Preparation, Machine Learning Fundamentals and Building LLM Applications with RAG.
6.8 Second project: from notebook to a weekly report
The first project was exploration: run a cell, look, run the next. Once it works, you'll want it to run every Monday without you. That means turning the steps into functions and writing the results to files other people can open. This is the same analysis, reorganised the way a script would be.
Python · step 1: each stage becomes a functiondef label_reviews(df):
"""Return a copy of df with sentiment, topic and summary columns added."""
results = df["text"].apply(classify_review).tolist()
return pd.concat([df.reset_index(drop=True), pd.json_normalize(results)], axis=1)
def summarise(df):
"""Return the headline numbers as a dictionary."""
return {
"reviews": len(df),
"negative": int((df["sentiment"] == "negative").sum()),
"share_negative": round(float((df["sentiment"] == "negative").mean()), 2),
"top_complaint": df.loc[df["sentiment"] == "negative", "topic"].mode().iat[0],
}
weekly = label_reviews(reviews)
print(summarise(weekly))
Python · step 2: write a report a manager can readdef write_report(df, path="weekly_report.md"):
stats = summarise(df)
lines = [
"# Customer review report",
"",
f"- Reviews analysed: {stats['reviews']}",
f"- Negative: {stats['negative']} ({stats['share_negative']:.0%})",
f"- Most common complaint: {stats['top_complaint']}",
"",
"## Negative reviews to follow up",
]
for _, row in df[df["sentiment"] == "negative"].iterrows():
lines.append(f"- ({row['topic']}) {row['text']}")
with open(path, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
return path
report = write_report(weekly)
weekly.to_csv("weekly_labels.csv", index=False) # the detail, for anyone who wants to check
print(open(report, encoding="utf-8").read())
Python · step 3: one function runs the whole jobdef main(df):
labelled_df = label_reviews(df)
if labelled_df["sentiment"].isna().any(): # a check that stops a bad report going out
raise ValueError("Some reviews could not be labelled: fix before reporting")
path = write_report(labelled_df)
print(f"Report written to {path} for {len(labelled_df)} reviews")
main(reviews)
Saved in a file called weekly_report.py, with main(pd.read_csv("this_week.csv")) at the bottom, those three cells are a program that can be scheduled. Notice what changed from the first project and what didn't. The analysis is identical. What's new is that each stage has a name and one job, the output goes to files, and there is a check that fails loudly instead of sending out a report with holes in it.
6.9 Before you share a project
A short check before your code, or its results, go to anyone else:
- Run it from the top in a fresh session. Code that only works because of a cell you ran an hour ago isn't finished.
- No secrets in the files — search for API keys and passwords before you send or commit anything.
- No personal data you don't need in the data, the outputs or the prompts.
- Say what the numbers are based on: how many records, from when, and what was left out.
- Say where AI was involved, and what share of its labels a person checked.
- Keep the inputs, so that someone can reproduce the result — including you, in three months.
This is also the point where an AI coding assistant is most useful — "turn these notebook cells into a script with functions and a main()" is a request they handle well — and where your review matters most, because a scheduled script runs with nobody watching.
Add a column urgent that is True when a review is negative and mentions delivery or damage, then print the urgent reviews for follow-up.
Your turn# Write your code here, then press RunShow a solution
labelled["urgent"] = (labelled["sentiment"] == "negative") & labelled["text"].str.contains(
"deliver|arriv|courier|damag|soaked|snapped", case=False)
print(labelled.loc[labelled["urgent"], ["id", "text"]])Write topic_table(df) that returns a few lines of text showing, for each topic, the number of reviews and how many were negative, sorted with the most negative first. Print the result for weekly. (Then, if you like, add it to write_report.)
Your turn# weekly comes from 6.8
# Write topic_table(df), then press RunShow a solution
def topic_table(df):
counts = df.groupby("topic").agg(reviews=("text", "count"),
negative=("sentiment", lambda s: int((s == "negative").sum())))
counts = counts.sort_values("negative", ascending=False)
return [f"- {topic}: {row['reviews']} reviews, {row['negative']} negative" for topic, row in counts.iterrows()]
print("\n".join(topic_table(weekly)))Key takeaways
- apply() runs a function over every row.
- json_normalize turns dictionary results into columns.
- Always check AI labels — count failures and read samples.
- Cross-tabs turn labels into insight.
- Virtual environments, scripts, Git and data protection keep projects healthy.
- To automate an analysis: one function per stage, outputs to files, and a main() that runs them.
- A scheduled script needs checks that stop it sending out a bad report.