Group, aggregate, and reshape

3.1.1

Summarize values by group and decide how missing categories affect the result.

On this page

Aggregate or transform

groupby splits data by key. agg reduces each group into summary values. transform returns values aligned to the original rows, useful for group means or shares. Pass dropna=False if a missing group key should appear in the output.

import pandas as pd

sales = pd.DataFrame({"item": ["Tea", "Tea", "Cake"], "units": [2, 4, 3]})
print(sales.groupby("item")["units"].sum().to_dict())
print(sales.groupby("item")["units"].transform("mean").tolist())
Three input rows form two groups. Tea rows with 2 and 4 units sum to 6. Cake has 3 units. Download image
A sum aggregation returns one result per item group.
Example output
{'Cake': 3, 'Tea': 6}
[3.0, 3.0, 3.0]

Compare groups with a pivot table

Use pivot when each index and column pair is unique. Use pivot_table with an explicit aggfunc when several records share a pair. Fill absent combinations with zero only if that matches what the missing combination means.

import pandas as pd

sales = pd.DataFrame({"item": ["Tea", "Tea", "Tea"], "store": ["A", "A", "B"], "units": [2, 4, 3]})
table = sales.pivot_table(index="item", columns="store", values="units", aggfunc="sum")
print(table.loc["Tea", ["A", "B"]].tolist())
Example output
[6, 3]

Official references