Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

GroupBy and Aggregat | Master Data Science with Python lesso | BraveProgrammer
  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 24 of 60

·python

GroupBy and Aggregations

20 minutes

Course progress40%

GroupBy for Summarizing Data

groupby splits data into groups, applies a function, then combines the results.

Simple groupby

total_sales = df.groupby('store_id')['revenue'].sum()
print(total_sales)

Multiple aggregations

agg = df.groupby([, ]).agg({
    : [, ],
    : 
})
(agg.head())
'store_id'
'product_id'
'units'
'sum'
'mean'
'revenue'
'sum'
print

Using named aggregation (pandas ≥ 0.25)

result = df.groupby('department').agg(
    total_employees=('employee_id', 'count'),
    avg_salary=('salary', 'mean')
)
print(result)

Transform vs. Apply

# Center units per store (subtract store mean)
centered = df.groupby('store_id')['units'].transform(lambda x: x - x.mean())
df['units_centered'] = centered

Filtering groups with filter

# Keep stores with total revenue > $1M
big_stores = df.groupby('store_id').filter(lambda x: x['revenue'].sum() > 1_000_000)

Info

agg returns a new DataFrame; transform preserves the original index.
Make it stickPractice what you've learned1 quiz · 4 practical tests · Optional activities from Master Data Science with PythonBrowse activities
Previous lessonData Cleaning: Duplicates, Renaming, and Type ConversionContinue to lesson 25Merging and Joining DataFramesBack to Master Data Science with Python curriculum