Lesson 23 of 23

PY-401 · Analysis end to end

Lab: Sales analysis

⏱ 9 min 🐍 Real Python 3 🎬 Animated

23of 23

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    ⚡ 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.

    Lab: Sales analysis, running
    1. import io
    2. import pandas as pd
    3. csv_text = """date,region,product,units,unit_price
    4. 2026-01-05,North,Tea,30,2.5
    5. 2026-01-12,South,Coffee,22,3.0
    6. 2026-01-19,East,Cake,8,4.5
    7. 2026-01-26,North,Coffee,25,3.0
    8. 2026-02-02,South,Tea,40,2.5
    9. 2026-02-09,East,Coffee,18,3.0
    10. 2026-02-16,North,Cake,12,4.5
    11. 2026-02-23,West,Tea,15,2.5
    12. 2026-03-02,North,Tea,35,2.5
    13. 2026-03-09,South,Cake,20,4.5
    14. 2026-03-16,East,Tea,28,2.5
    15. 2026-03-23,West,Coffee,30,3.0
    16. 2026-03-30,North,Coffee,33,3.0
    17. """
    18. df = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"])
    19. df["revenue"] = df["units"] * df["unit_price"]
    20. monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum()
    21. by_region = df.groupby("region")["revenue"].sum().sort_values(ascending=False)
    22. by_product = df.groupby("product")["revenue"].sum().sort_values(ascending=False)
    23. print(monthly)
    24. print("Best month:", monthly.idxmax())
    25. print("Best region:", by_region.idxmax(), by_region.max())
    26. print("Best product:", by_product.idxmax(), by_product.max())
    27. ax = monthly.plot(marker="o", figsize=(6, 3), title="March was the best month by far")
    28. ax.set_ylabel("Revenue")
    Press ▶ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideadf["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.
    3. 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()

    ▶ Run the example 🎬 Watch it come alive

    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).

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. How do you add a revenue column?
    2. 2. What does idxmax() return on a Series?
    3. 3. Why parse_dates when loading?
    4. 4. Which chart suits revenue per month?
    5. 5. Top product by units and by revenue can differ because…

    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