Editor

Filter Groups by Size

Advanced · Write the code · from Pandas GroupBy: Split-Apply-Combine for Powerful Aggregations

From the lesson: Pandas GroupBy: Split-Apply-Combine for Powerful Aggregations

Imagine you have a giant pile of receipts from a store. You want to know how much each department earned last month. What do you do? You sort the receipts into piles by department, add up each pile, and write down the totals.

Read the lesson

Filter df to keep only teams that have more than 2 members. Print the name column of the filtered DataFrame as a list.

Use groupby().filter() with a lambda.

import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Frank'],
'team': ['Red', 'Blue', 'Red', 'Red', 'Blue', 'Green']
})
# Filter to keep teams with more than 2 members

More Pandas GroupBy exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz