Data Science ยท Chapter 11 of 43
GroupBy & Aggregation
GROUPBY splits a DataFrame by one or more columns, applies a function per group, and combines the results (SPLIT-APPLY-COMBINE).
Essential for reporting: per-city sales, per-user activity, etc.
Example 1 (python)
import pandas as pd
df = pd.read_csv('sales.csv')
print(df.groupby('city')['amount'].sum())Total sales per city.
Example 2 (python)
print(df.groupby('city').agg(total=('amount','sum'), n=('amount','count')))Multiple named aggregations.
Key points
- Split โ apply โ combine.
- Aggregate with sum, mean, count, etc.
- agg() supports multiple metrics.
- Foundation of dashboards.
๐ก Note: `agg` with named outputs (`total=('amount','sum')`) is the modern, readable way to write multi-metric groupbys.
