PY-401 · Analysis end to end
Lab: Sales analysis
⏱ 9 min 🐍 Real Python 3 🎬 Animated ✓ Completed
⚡ The 30-second answer
A sales analysis loads the raw export, adds the numbers you need (revenue = units × price), and answers each business question with one groupby: revenue by month, by region and by product. idxmax() names the winner of each, and a line chart shows the trend for the slide. This lab combines every module of PY-401 in about 20 lines.
- Load and prepare a real-looking export
- Answer three questions with groupby and idxmax
- Present the trend as a chart
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import ioimport pandas as pdcsv_text = """date,region,product,units,unit_price2026-01-05,North,Tea,30,2.52026-01-12,South,Coffee,22,3.02026-01-19,East,Cake,8,4.52026-01-26,North,Coffee,25,3.02026-02-02,South,Tea,40,2.52026-02-09,East,Coffee,18,3.02026-02-16,North,Cake,12,4.52026-02-23,West,Tea,15,2.52026-03-02,North,Tea,35,2.52026-03-09,South,Cake,20,4.52026-03-16,East,Tea,28,2.52026-03-23,West,Coffee,30,3.02026-03-30,North,Coffee,33,3.0"""df = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"])df["revenue"] = df["units"] * df["unit_price"]monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum()by_region = df.groupby("region")["revenue"].sum().sort_values(ascending=False)by_product = df.groupby("product")["revenue"].sum().sort_values(ascending=False)print(monthly)print("Best month:", monthly.idxmax())print("Best region:", by_region.idxmax(), by_region.max())print("Best product:", by_product.idxmax(), by_product.max())ax = monthly.plot(marker="o", figsize=(6, 3), title="March was the best month by far")ax.set_ylabel("Revenue")
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
date
2026-01 252.0
2026-02 245.5
2026-03 436.5
Freq: M, Name: revenue, dtype: float64
Best month: 2026-03
Best region: North 390.5
Best product: Coffee 384.0 🎯 Using the same data, set units_by_product to total units per product, and top_units to the product that sold the most units. Is it the same as the top revenue product?
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
units_by_product = df.groupby("product")["units"].sum(); top_units = units_by_product.idxmax()
- The problemIt is the first Monday of April. The owner of a small café chain wants three answers before lunch: best month, best region, best product. You have a CSV export and the skills from this course.
- The Python idea
df["revenue"] = df["units"] * df["unit_price"]A sales analysis loads the raw export, adds the numbers you need (revenue = units × price), and answers each business question with one groupby: revenue by month, by region and by product. - In real lifeThis is the weekly job of a retail analyst: the same groupbys on a fresh export every Monday, often turned into a scheduled script (PY-310 Automation) or a dashboard (PY-410).
Start with a question
It is the first Monday of April. The owner of a small café chain wants three answers before lunch: best month, best region, best product. You have a CSV export and the skills from this course.
Employers hire analysts to turn exports into decisions. This end-to-end flow is the exact work of a junior data analyst, and it makes a strong first portfolio project.
Explain it like I'm 10
You have a big pile of receipts. You add up money per month, per shop and per item, then point at the biggest pile in each. That is the whole analysis.
The technical explanation
Load and fix types: read_csv(..., parse_dates=["date"]), so dates group by month.
Add measures: df["revenue"] = df["units"] * df["unit_price"] is vectorised maths from module 1.
Answer with groupby: df.groupby(df["date"].dt.to_period("M"))["revenue"].sum() gives revenue per month. idxmax() returns the label of the biggest value.
Present: plot the monthly series as a line with a title that states the finding. Save your notebook and the chart to a GitHub repo as a portfolio piece.
Syntax
df["revenue"] = df["units"] * df["unit_price"]
monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum()
monthly.idxmax() Real-world scenario
This is the weekly job of a retail analyst: the same groupbys on a fresh export every Monday, often turned into a scheduled script (PY-310 Automation) or a dashboard (PY-410).
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
🏆 Every lesson counts toward your certificate Take the PY-401 practice exam →Questions people ask
How do I group sales by month in pandas?
Make sure the date column is a datetime (parse_dates or pd.to_datetime), then group by df["date"].dt.to_period("M"), or use df.resample("MS", on="date") for a time-series result.
Is a sales analysis a good data analyst portfolio project?
Yes, if it starts from a raw file, shows the cleaning steps, answers clear business questions and ends with one or two charts and a written conclusion. Put it in a GitHub repository with a short README.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I group sales by month in pandas?
Make sure the date column is a datetime (parse_dates or pd.to_datetime), then group by df["date"].dt.to_period("M"), or use df.resample("MS", on="date") for a time-series result.
beginner Is a sales analysis a good data analyst portfolio project?
Yes, if it starts from a raw file, shows the cleaning steps, answers clear business questions and ends with one or two charts and a written conclusion. Put it in a GitHub repository with a short README.
intermediate How do you add a revenue column?
df["revenue"] = df["units"] * df["unit_price"]. Vectorised maths creates the column in one line.
intermediate What does idxmax() return on a Series?
The label of the largest value. idxmax names the winner, such as the best region.
Quick revision
Remember
- Load and prepare a real-looking export
- Answer three questions with groupby and idxmax
- Present the trend as a chart
- Answer the question that was asked, then add one surprise you found. "Tea sold most units, but Coffee made the most money" is the kind of line people remember.
Syntax
df["revenue"] = df["units"] * df["unit_price"]
monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum()
monthly.idxmax() Official documentation
- Time series: periods (docs.python.org)
- pandas.Series.idxmax (docs.python.org)