Lesson 4: Grouping and sorting
    1 / 10

    Lesson 4 of 6 · about 20 minutes

    Grouping and sorting

    Grouping

    Many questions are about groups: total sales per shop, average score per class, number of pets per animal. groupby() splits a table into groups by the values in a column, runs a summary on each group, and puts the answers together.

    import pandas as pd
    
    sales = pd.DataFrame({
        "shop": ["North", "South", "North", "East", "South", "North"],
        "fruit": ["apple", "apple", "pear", "pear", "pear", "apple"],
        "boxes": [12, 7, 9, 4, 10, 15],
    })
    print(sales.groupby("shop")["boxes"].sum())

    The output:

    shop
    East      4
    North    36
    South    17
    Name: boxes, dtype: int64

    Read it as: group the rows by shop, take the boxes column, and add it up for each group. Swap sum() for mean(), max(), min() or count() to ask a different question. size() counts the rows in each group:

    import pandas as pd
    
    sales = pd.DataFrame({
        "shop": ["North", "South", "North", "East", "South", "North"],
        "boxes": [12, 7, 9, 4, 10, 15],
    })
    print(sales.groupby("shop").size())
    print(sales.groupby("shop")["boxes"].mean())

    The output:

    shop
    East     1
    North    3
    South    2
    dtype: int64
    shop
    East      4.0
    North    12.0
    South     8.5
    Name: boxes, dtype: float64