GroupBy, Aggregation, and Pivot Tables
Summarize data with groupby operations and pivot tables.
groupby Basics
df.groupby("col") splits the DataFrame into groups by unique values of the column. Chain an aggregation to get results.
import pandas as pd
df = pd.DataFrame({
"dept":["HR","IT","HR","IT","HR"],
"salary":[60,80,65,90,70]
})
print(df.groupby("dept")["salary"].mean())
# HR 65.0
# IT 85.0Multiple Aggregation Functions
Use agg() to apply multiple aggregation functions at once.
import pandas as pd
df = pd.DataFrame({"dept":["HR","IT","HR","IT"],"sal":[60,80,65,90]})
result = df.groupby("dept")["sal"].agg(["mean","max","count"])
print(result)All lessons in this course
- Series and DataFrame Fundamentals
- Indexing, Filtering, and Boolean Masks
- GroupBy, Aggregation, and Pivot Tables
- Merging, Joining, and Data Cleaning