We use filter() to keep or remove whole groups in data based on a rule. It helps us focus on groups that matter.
filter() for group-level filtering in Pandas
grouped_data.filter(function) # where grouped_data is a DataFrameGroupBy object # function takes a group (DataFrame) and returns True or False
The function receives each group as a small DataFrame.
If the function returns True, the whole group is kept; if False, it is removed.
df.groupby('Category').filter(lambda x: len(x) > 3)
df.groupby('Team').filter(lambda x: x['Score'].mean() > 80)
df.groupby('Month').filter(lambda x: x['Sales'].sum() > 1000)
This code keeps only teams where the average player score is >= 75. Teams A and B meet this condition, so their rows stay. Team C is removed.
import pandas as pd data = { 'Team': ['A', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C'], 'Player': ['John', 'Mike', 'Anna', 'Tom', 'Sara', 'Bob', 'Liz', 'Sam', 'Eva'], 'Score': [90, 85, 70, 75, 80, 60, 65, 70, 55] } df = pd.DataFrame(data) # Group by 'Team' and keep only teams with average Score >= 75 filtered_df = df.groupby('Team').filter(lambda x: x['Score'].mean() >= 75) print(filtered_df)
The filter() method returns a DataFrame with only the groups that pass the test.
Inside the lambda, you can use any condition based on the group's data.
If no groups pass, the result is an empty DataFrame.
filter() helps keep or remove whole groups based on a condition.
It works on grouped data and returns only groups where the condition is True.
Use it to focus analysis on important groups easily.
Practice
filter() function do when applied to a grouped pandas DataFrame?Solution
Step 1: Understand the purpose of
Thefilter()on groupsfilter()function is used on grouped data to keep or remove whole groups based on a condition applied to the group as a whole.Step 2: Differentiate from row-level filtering
Unlike filtering rows inside groups,filter()returns entire groups only if the condition is True for that group.Final Answer:
Keeps or removes entire groups based on a condition -> Option CQuick Check:
Group-level filtering = Keeps/removes groups [OK]
- Thinking filter() filters rows inside groups
- Confusing filter() with aggregation functions
- Assuming filter() sorts groups
df grouped by column 'Category' to keep groups with more than 3 rows?Solution
Step 1: Recall correct
The correct syntax is to group by a column, then callfilter()syntax on grouped datafilter()with a function that takes each group and returns True or False.Step 2: Check each option
df.groupby('Category').filter(lambda x: len(x) > 3) correctly groups by 'Category' and filters groups with length > 3. Options A, B, and D use incorrect syntax or wrong method calls.Final Answer:
df.groupby('Category').filter(lambda x: len(x) > 3) -> Option AQuick Check:
Correct syntax = groupby + filter(lambda x: condition) [OK]
- Using filter() without groupby()
- Passing wrong arguments to filter()
- Confusing apply() with filter()
df below:import pandas as pd
data = {'Team': ['A', 'A', 'B', 'B', 'B', 'C'], 'Points': [10, 15, 10, 5, 7, 20]}
df = pd.DataFrame(data)
filtered = df.groupby('Team').filter(lambda x: x['Points'].sum() > 20)
print(filtered)What will be the output?
Solution
Step 1: Calculate sum of Points per Team
Team A: 10 + 15 = 25, Team B: 10 + 5 + 7 = 22, Team C: 20Step 2: Apply filter condition sum > 20
Teams A and B have sums > 20, Team C has 20 (not > 20), so only A and B groups pass.Step 3: Check printed rows
Filtered DataFrame includes rows from Teams A and B only.Final Answer:
Rows where Team is 'A' and 'B' -> Option BQuick Check:
Sum > 20 keeps Teams A and B [OK]
- Forgetting to include Team A rows
- Including Team C because sum equals 20
- Confusing sum with mean
df.groupby('Category').filter(lambda x: x['Value'] > 10)Why will this code raise an error?
Solution
Step 1: Understand filter() expects a boolean scalar per group
The function inside filter() must return a single True or False for the whole group.Step 2: Analyze the lambda function
The lambda returns a Series of booleans (x['Value'] > 10) for each row, not a single boolean.Final Answer:
Because the lambda returns a Series, not a single True/False value -> Option AQuick Check:
filter() needs single True/False per group [OK]
- Returning a Series instead of a scalar boolean
- Thinking filter() works like row-level filter
- Misunderstanding filter() usage after groupby
df with columns 'Store', 'Sales', and 'Month'. You want to keep only stores where the average monthly sales are above 5000. Which code correctly filters the DataFrame using filter()?Solution
Step 1: Identify correct use of filter() with groupby
We must group by 'Store' and use filter() with a lambda returning True if the group's average sales > 5000.Step 2: Check each option
df.groupby('Store').filter(lambda x: x['Sales'].mean() > 5000) correctly usesfilter()withlambda x: x['Sales'].mean() > 5000. df.filter(lambda x: x['Sales'].mean() > 5000, groupby='Store') has wrong syntax, C uses apply which returns a Series, and D compares sales values directly, not the mean.Final Answer:
df.groupby('Store').filter(lambda x: x['Sales'].mean() > 5000) -> Option DQuick Check:
Use groupby + filter with mean condition [OK]
- Using filter() without groupby()
- Comparing individual sales instead of group mean
- Using apply() instead of filter() for filtering groups
Ready to prove it?
Pass the test and this pattern moves unknown
