Lesson 15 of 23
โฎPrev Nextโฏ

PY-401 ยท Summarising and joining

groupby: totals per group

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

15of 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

    groupby splits a table into groups that share a value, runs a calculation on each group and puts the results back together. sales.groupby("region")["revenue"].sum() gives one total per region. Use .agg(["sum", "mean", "count"]) for several results at once, and a list of columns to group by two things.

    • Total a column per group
    • Get several statistics with agg
    • Group by two columns

    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.

    groupby: totals per group, running
    1. import pandas as pd
    2. sales = pd.DataFrame({
    3. "region": ["North", "South", "North", "East", "South", "North"],
    4. "product": ["Tea", "Tea", "Cake", "Tea", "Cake", "Tea"],
    5. "revenue": [120, 90, 200, 60, 150, 80],
    6. })
    7. print(sales.groupby("region")["revenue"].sum())
    8. print(sales.groupby("region")["revenue"].agg(["sum", "mean", "count"]).round(1))
    9. print(sales.groupby(["region", "product"])["revenue"].sum().reset_index())
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemThe sales director asks one question every Monday: "How much did each region make?" Six rows today, sixty thousand next year. The answer is the same single line.
    2. The Python ideadf.groupby("key")["col"].sum()groupby splits a table into groups that share a value, runs a calculation on each group and puts the results back together.
    3. In real lifeA ride-hailing company runs trips.groupby("driver_id")["rating"].mean() every night and contacts drivers whose average drops below 4.5.

    Start with a question

    The sales director asks one question every Monday: "How much did each region make?" Six rows today, sixty thousand next year. The answer is the same single line.

    Most business questions are "per something": revenue per region, orders per customer, average score per class. groupby answers all of them.

    Explain it like I'm 10

    Tip a bag of sweets on the table and sort them into piles by colour. Then count each pile. groupby is the sorting into piles, sum or count is what you do with each pile.

    The technical explanation

    Read df.groupby("region")["revenue"].sum() as: split by region, take the revenue column, add up each group.

    Any aggregation works after groupby: sum, mean, count, min, max, median, nunique.

    .agg(["sum", "mean", "count"]) returns one column per statistic. Named aggregation, .agg(total=("revenue", "sum")), lets you name the result columns.

    groupby(["region", "product"]) makes one group per combination. .reset_index() turns the result back into a flat table.

    Syntax

    df.groupby("key")["col"].sum()
    df.groupby("key")["col"].agg(["sum", "mean"])
    df.groupby(["a", "b"])["col"].sum().reset_index()

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    A ride-hailing company runs trips.groupby("driver_id")["rating"].mean() every night and contacts drivers whose average drops below 4.5.

    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. What does df.groupby("city")["sales"].sum() return?
    2. 2. Which counts rows in each group?
    3. 3. What becomes the index of a groupby result?
    4. 4. How do you get sum and mean together?
    5. 5. groupby(["region", "product"]) makes groups forโ€ฆ

    Questions people ask

    How do I get a DataFrame instead of a Series from pandas groupby?

    Add .reset_index() to the result, or pass as_index=False to groupby. Both give you a flat table with the group values as a normal column.

    What is the difference between count and size in pandas groupby?

    count gives the number of non-missing values in each column per group. size gives the number of rows per group, including rows with missing values.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner How do I get a DataFrame instead of a Series from pandas groupby?

    Add .reset_index() to the result, or pass as_index=False to groupby. Both give you a flat table with the group values as a normal column.

    beginner What is the difference between count and size in pandas groupby?

    count gives the number of non-missing values in each column per group. size gives the number of rows per group, including rows with missing values.

    intermediate What does df.groupby("city")["sales"].sum() return?

    One total per city. groupby makes one group per city and sums each.

    intermediate Which counts rows in each group?

    .count(). count gives the number of non-missing values per group.

    Quick revision

    Remember

    • Total a column per group
    • Get several statistics with agg
    • Group by two columns
    • The groups become the index of the result. Add .reset_index() to turn them back into a normal column before you save, merge or plot.

    Syntax

    df.groupby("key")["col"].sum()
    df.groupby("key")["col"].agg(["sum", "mean"])
    df.groupby(["a", "b"])["col"].sum().reset_index()

    Official documentation