Bird
Raised Fist0
Pandasdata~20 mins

filter() for group-level filtering in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Master of group-level filtering
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of group filtering with filter()
What is the output DataFrame after applying the filter to keep groups with sum of values greater than 10?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Category': ['A', 'A', 'B', 'B', 'C', 'C'],
    'Value': [4, 8, 3, 2, 7, 6]
})
filtered = df.groupby('Category').filter(lambda x: x['Value'].sum() > 10)
print(filtered)
A
Empty DataFrame
Columns: [Category, Value]
Index: []
B
  Category  Value
2        B      3
3        B      2
C
  Category  Value
0        A      4
1        A      8
2        B      3
3        B      2
4        C      7
5        C      6
D
  Category  Value
0        A      4
1        A      8
4        C      7
5        C      6
Attempts:
2 left
💡 Hint
Sum the 'Value' column for each group and keep groups where sum > 10.
❓ data_output
intermediate
1:30remaining
Number of rows after group-level filter
After filtering groups where the mean of 'Score' is at least 75, how many rows remain in the DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Team': ['X', 'X', 'Y', 'Y', 'Z', 'Z', 'Z'],
    'Score': [80, 70, 60, 90, 75, 85, 65]
})
filtered = df.groupby('Team').filter(lambda g: g['Score'].mean() >= 75)
print(len(filtered))
A4
B5
C7
D3
Attempts:
2 left
💡 Hint
Calculate mean score per team and count rows of teams meeting the condition.
🔧 Debug
advanced
1:30remaining
Identify the error in group filtering code
What error will this code raise when run?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Group': ['G1', 'G1', 'G2', 'G2'],
    'Value': [10, 20, 5, 15]
})
filtered = df.groupby('Group').filter(lambda x: x['Value'].sum > 20)
print(filtered)
ATypeError: '>' not supported between instances of 'method' and 'int'
BKeyError: 'Value'
CSyntaxError: invalid syntax
DNo error, prints filtered DataFrame
Attempts:
2 left
💡 Hint
Check if sum is called as a method or accessed as an attribute.
🚀 Application
advanced
2:00remaining
Filter groups with at least 3 rows and max value > 50
Which code correctly filters groups in DataFrame df where each group has at least 3 rows and the maximum 'Score' is greater than 50?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Category': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'C'],
    'Score': [40, 55, 60, 30, 45, 70, 65, 50, 40]
})
Adf.groupby('Category').filter(lambda g: len(g) > 3 and g['Score'].max() >= 50)
Bdf.groupby('Category').filter(lambda g: len(g) >= 3 and g['Score'].max() > 50)
Cdf.groupby('Category').filter(lambda g: g['Score'].max() > 50 or len(g) >= 3)
Ddf.groupby('Category').filter(lambda g: len(g) >= 3 and g['Score'].max() >= 50)
Attempts:
2 left
💡 Hint
Both conditions must be true: group size at least 3 and max score greater than 50.
🧠 Conceptual
expert
1:30remaining
Understanding filter() behavior on empty groups
If a group in a pandas groupby object is empty, what will be the behavior of filter() when the filtering function returns True for that group?
AThe empty group will be excluded from the result regardless of the filter function.
BThe entire DataFrame will be returned unfiltered.
Cfilter() will raise a ValueError due to empty group.
DThe empty group will be included in the result as an empty DataFrame slice.
Attempts:
2 left
💡 Hint
Consider if empty groups have any rows to include.

Practice

(1/5)
1. What does the filter() function do when applied to a grouped pandas DataFrame?
easy
A. Sorts groups by their size
B. Filters rows inside each group individually
C. Keeps or removes entire groups based on a condition
D. Aggregates data by calculating group means

Solution

  1. Step 1: Understand the purpose of filter() on groups

    The filter() function is used on grouped data to keep or remove whole groups based on a condition applied to the group as a whole.
  2. 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.
  3. Final Answer:

    Keeps or removes entire groups based on a condition -> Option C
  4. Quick Check:

    Group-level filtering = Keeps/removes groups [OK]
Hint: Remember: filter() keeps or drops whole groups [OK]
Common Mistakes:
  • Thinking filter() filters rows inside groups
  • Confusing filter() with aggregation functions
  • Assuming filter() sorts groups
2. Which of the following is the correct syntax to filter groups in a pandas DataFrame df grouped by column 'Category' to keep groups with more than 3 rows?
easy
A. df.groupby('Category').filter(lambda x: len(x) > 3)
B. df.filter(groupby='Category', condition=lambda x: len(x) > 3)
C. df.groupby('Category').apply(filter(len(x) > 3))
D. df.filter(lambda x: x['Category'] > 3)

Solution

  1. Step 1: Recall correct filter() syntax on grouped data

    The correct syntax is to group by a column, then call filter() with a function that takes each group and returns True or False.
  2. 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.
  3. Final Answer:

    df.groupby('Category').filter(lambda x: len(x) > 3) -> Option A
  4. Quick Check:

    Correct syntax = groupby + filter(lambda x: condition) [OK]
Hint: Use groupby().filter(lambda x: condition) for group filtering [OK]
Common Mistakes:
  • Using filter() without groupby()
  • Passing wrong arguments to filter()
  • Confusing apply() with filter()
3. Given the DataFrame 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?
medium
A. Rows where Team is 'A' and 'C'
B. Rows where Team is 'A' and 'B'
C. Rows where Team is 'B' only
D. All rows

Solution

  1. Step 1: Calculate sum of Points per Team

    Team A: 10 + 15 = 25, Team B: 10 + 5 + 7 = 22, Team C: 20
  2. Step 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.
  3. Step 3: Check printed rows

    Filtered DataFrame includes rows from Teams A and B only.
  4. Final Answer:

    Rows where Team is 'A' and 'B' -> Option B
  5. Quick Check:

    Sum > 20 keeps Teams A and B [OK]
Hint: Sum group values, keep groups where sum > 20 [OK]
Common Mistakes:
  • Forgetting to include Team A rows
  • Including Team C because sum equals 20
  • Confusing sum with mean
4. Consider this code snippet:
df.groupby('Category').filter(lambda x: x['Value'] > 10)

Why will this code raise an error?
medium
A. Because the lambda returns a Series, not a single True/False value
B. Because filter() cannot be used after groupby()
C. Because 'Value' column does not exist
D. Because filter() requires a list, not a lambda

Solution

  1. 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.
  2. Step 2: Analyze the lambda function

    The lambda returns a Series of booleans (x['Value'] > 10) for each row, not a single boolean.
  3. Final Answer:

    Because the lambda returns a Series, not a single True/False value -> Option A
  4. Quick Check:

    filter() needs single True/False per group [OK]
Hint: Lambda must return one True/False per group, not Series [OK]
Common Mistakes:
  • Returning a Series instead of a scalar boolean
  • Thinking filter() works like row-level filter
  • Misunderstanding filter() usage after groupby
5. You have a sales DataFrame 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()?
hard
A. df.filter(lambda x: x['Sales'].mean() > 5000, groupby='Store')
B. df.groupby('Store').filter(lambda x: x['Sales'] > 5000)
C. df.groupby('Store').apply(lambda x: x['Sales'].mean() > 5000)
D. df.groupby('Store').filter(lambda x: x['Sales'].mean() > 5000)

Solution

  1. 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.
  2. Step 2: Check each option

    df.groupby('Store').filter(lambda x: x['Sales'].mean() > 5000) correctly uses filter() with lambda 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.
  3. Final Answer:

    df.groupby('Store').filter(lambda x: x['Sales'].mean() > 5000) -> Option D
  4. Quick Check:

    Use groupby + filter with mean condition [OK]
Hint: Filter groups by mean with groupby().filter(lambda x: x['col'].mean() > val) [OK]
Common Mistakes:
  • Using filter() without groupby()
  • Comparing individual sales instead of group mean
  • Using apply() instead of filter() for filtering groups
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard