Pandas Group By

Summarise data by category.

✍️ 3 exercises + code challenge in this lesson

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.

Key Takeaways: Pandas Group By

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.

Pandas Group By Code Example

Pandas
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())
Output
dept
HR        95000.0
IT       110000.0
Sales     88000.0
Name: salary, dtype: float64
{'IT': 3, 'HR': 1, 'Sales': 1}
Free sign-in required · Google login available

Pandas Group By Practice Exercises

Check what you learned in “Pandas Group By”.

/ 3 solved
Fill in the blank

Group rows by department.

df.("dept")["salary"].mean()
✓ Correct! Not quite. Try again.
Multiple choice

Which method counts how often each value appears?

✓ Correct! Not quite. Try again.
Code challenge

Print the total salary of the IT department (use groupby and sum).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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