Formation
90 min read
Data Manipulation with Pandas
π¦ Groupby and Aggregation with Pandas
Learning objectives
π― Objectives:\n
1Use groupby\n2. Apply aggregations\n3. Use agg()\n4. Understand transform()
Introduction
π Groupby allows analyzing data by category.
Theoretical content
Groupby:\n
PYTHON
\ndf.groupby("category").mean()\nPractical examples
π» Example: Sales analysis by region\n
PYTHON
\nsales.groupby("region")["sales"].sum()\nBest practices
1Use agg() for multiple aggregations\nβ
2. Use transform() to add columns\nβ
3. Use reset_index() to get normal DataFrame\nβ
4. Use as_index=False in groupby
Common pitfalls
Forgetting that groupby returns a GroupBy object\n
Apply an aggregation after groupby
Summary
groupby(): grouping\nβ
agg(): multiple aggregations\nβ
transform(): add columns\nβ
reset_index(): normal DataFrame
Additional resources
π pandas.pydata.org/docs/user_guide/groupby.html