groupby() basics
groupby splits rows into groups by a column, so you can summarize each group separately.
In this page:
Syntax
df.groupby("column")
df.groupby("column")["value_column"].sum()
groupby() basics
df.groupby("col") creates a lazy grouping object. Applying an aggregation like sum, mean or count computes one result per group. It follows a split-apply-combine pattern. The group keys become the index of the result.
Note:
Use as_index=False to keep the group column as a regular column.
Example: groupby() basics
import pandas as pd
df = pd.DataFrame({"dept": ["A", "B", "A", "B"], "salary": [100, 200, 150, 250]})
print(df.groupby("dept")["salary"].sum())
print(df.groupby("dept", as_index=False)["salary"].mean())
# Output:
# dept
# A 250
# B 450
# Name: salary, dtype: int64
# dept salary
# 0 A 125.0
# 1 B 225.0
Related Topics
Common Mistakes
- Forgetting to apply an aggregation
- Losing the key to the index unintentionally
- Grouping by a column with NaN, which is dropped by default
Chapter Summary
- groupby splits data into groups
- Aggregations run per group
- Keys become the index
- as_index=False keeps them as a column
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: