df.groupby("column") splits rows into groups, then an aggregate function summarises each group:
df.groupby("dept")["salary"].mean()- Several at once:
.agg(["count", "mean", "max"]) df["city"].value_counts()counts each value.
Summarise data by category.
✍️ 3 exercises + code challenge in this lessondf.groupby("column") splits rows into groups, then an aggregate function summarises each group:
df.groupby("dept")["salary"].mean().agg(["count", "mean", "max"])df["city"].value_counts() counts each value.Mastering Pandas Group By helps you write clean and reliable Pandas code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
import pandas as pd
df = pd.DataFrame({
"dept": ["IT", "HR", "IT", "Sales", "IT"],
"salary": [120000, 95000, 110000, 88000, 100000],
})
print(df.groupby("dept")["salary"].mean())
print(df["dept"].value_counts().to_dict())
dept
HR 95000.0
IT 110000.0
Sales 88000.0
Name: salary, dtype: float64
{'IT': 3, 'HR': 1, 'Sales': 1}
Check what you learned in “Pandas Group By”.
Group rows by department.
df.("dept")["salary"].mean()
Which method counts how often each value appears?
Print the total salary of the IT department (use groupby and sum).
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services