🎓 A1Learner
🔍
0 of 50 lessons completed

Grouping and Adding Up

groupby splits rows into groups by a shared value. Each group then gets one summary number.

Add up units by category

groupby splits the rows by category. sum adds up the units in each group.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "units": [2, 1, 3, 5],
})
print(df.groupby("category")["units"].sum())

Average price by category

mean averages the price in each group. Drink averages 5.25 here.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "category": ["Drink", "Drink", "Home", "Office"],
    "price": [4.50, 6.00, 12.00, 2.00],
})
print(df.groupby("category")["price"].mean())

Groups by region

Any column can split the rows. This frame groups the same units by region.

import pandas as pd

df = pd.DataFrame({
    "product": ["Tea", "Coffee", "Mug", "Pen"],
    "region": ["North", "South", "East", "North"],
    "units": [2, 1, 3, 5],
})
print(df.groupby("region")["units"].sum())

Example

import io
import pandas as pd

SALES_CSV = """order_id,date,product,category,units,price,region
101,2026-01-05,Tea,Drink,2,4.50,North
102,2026-01-06,Coffee,Drink,1,6.00,South
103,2026-01-07,Mug,Home,3,12.00,East
104,2026-01-08,Notebook,Office,2,8.50,West
105,2026-01-09,Pen,Office,5,2.00,North
106,2026-01-12,Lamp,Home,1,24.00,South
107,2026-01-13,Tea,Drink,4,4.50,East
108,2026-01-14,Coffee,Drink,2,6.00,West
109,2026-01-15,Mug,Home,1,12.00,North
110,2026-01-16,Notebook,Office,3,8.50,South
111,2026-01-19,Pen,Office,2,2.00,East
112,2026-01-20,Lamp,Home,2,24.00,West"""

sales = pd.read_csv(io.StringIO(SALES_CSV))
print(sales.groupby("category")["units"].sum())
print(sales.groupby("category")["price"].mean())

Key points

  • Use groupby to split rows by the values in one column.
  • Pick one column after groupby to work on that column only.
  • Add sum after groupby to add up each group.
  • Add mean after groupby to average each group.
  • The grouping column becomes the index of the result.

In this example, the sales table loads from the CSV text. groupby splits the rows by category. The first print adds up the units in each group, and the second print averages the price. Home sold 7 units in total, and its average price is the highest of the three.

Note

groupby lists the group names from A to Z by default.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which call adds up units for each category?