Bird
Raised Fist0
Pandasdata~20 mins

GroupBy with pipe for chaining in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
GroupBy Pipe Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of GroupBy with pipe chaining
What is the output of this code snippet using pandas GroupBy and pipe chaining?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Team': ['A', 'A', 'B', 'B', 'C', 'C'],
    'Points': [10, 15, 10, 20, 5, 10],
    'Assists': [5, 7, 8, 6, 2, 3]
})

result = (df.groupby('Team')
            .pipe(lambda d: d['Points'].sum())
            .pipe(lambda s: s.sort_values(ascending=False)))

print(result)
A
Team
B    30
A    25
C    15
Name: Points, dtype: int64
B
Team
C    15
A    25
B    30
Name: Points, dtype: int64
C
Team
A    25
B    30
C    15
Name: Points, dtype: int64
D{'A': 25, 'B': 30, 'C': 15}
Attempts:
2 left
💡 Hint
Remember that pipe passes the object to the function and you can chain operations.
❓ data_output
intermediate
1:30remaining
Resulting DataFrame shape after GroupBy with pipe
After running this code, what is the shape of the resulting DataFrame?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Category': ['X', 'X', 'Y', 'Y', 'Z'],
    'Value': [1, 2, 3, 4, 5],
    'Score': [10, 20, 30, 40, 50]
})

result = (df.groupby('Category')
            .pipe(lambda d: d.agg({'Value': 'sum', 'Score': 'mean'}))
            .reset_index())

print(result.shape)
A(3, 3)
B(3, 2)
C(5, 3)
D(5, 2)
Attempts:
2 left
💡 Hint
Check how many unique categories and how many aggregated columns.
🔧 Debug
advanced
1:30remaining
Identify the error in GroupBy pipe chaining
What error will this code raise when executed?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Group': ['G1', 'G1', 'G2'],
    'Data': [10, 20, 30]
})

result = (df.groupby('Group')
            .pipe(lambda d: d['Data'].mean())
            .pipe(lambda s: s.reset_index(drop=True)))

print(result)
AAttributeError: 'float' object has no attribute 'reset_index'
BNo error, prints a Series
CKeyError: 'Data'
DTypeError: 'DataFrameGroupBy' object is not subscriptable
Attempts:
2 left
💡 Hint
Check what the first pipe returns and what the second pipe tries to do.
🚀 Application
advanced
2:00remaining
Using pipe to filter groups after aggregation
Which option produces a DataFrame with groups having sum of 'Sales' greater than 100 using pipe chaining?
Pandas
import pandas as pd

df = pd.DataFrame({
    'Store': ['S1', 'S1', 'S2', 'S2', 'S3'],
    'Sales': [50, 60, 40, 30, 120]
})

result = (df.groupby('Store')
            .pipe(lambda d: d['Sales'].sum())
            .pipe(lambda s: s[s > 100])
            .reset_index())

print(result)
A
  Store  Sales
0    S1    110
1    S2     70
B
  Store  Sales
0    S2     70
1    S3    120
C
  Store  Sales
0    S1    110
1    S3    120
D
  Store  Sales
0    S3    120
Attempts:
2 left
💡 Hint
Sum sales per store, then filter sums greater than 100.
🧠 Conceptual
expert
1:30remaining
Why use pipe in GroupBy chaining?
What is the main advantage of using pipe in pandas GroupBy chaining?
AIt automatically optimizes the GroupBy operation for faster computation.
BIt converts the GroupBy object into a DataFrame immediately.
CIt replaces the need for aggregation functions like sum or mean.
DIt allows applying custom functions in the middle of method chains without breaking the flow.
Attempts:
2 left
💡 Hint
Think about how pipe helps keep code readable and chainable.

Practice

(1/5)
1. What is the main benefit of using pipe with groupby in pandas?
easy
A. It changes the data type of grouped columns.
B. It automatically sorts the groups in ascending order.
C. It allows chaining custom functions for clearer and cleaner code.
D. It removes missing values from the groups.

Solution

  1. Step 1: Understand the role of pipe

    pipe passes the grouped data to a custom function, enabling chaining.
  2. Step 2: Recognize the benefit in code clarity

    This chaining makes the code easier to read and maintain by avoiding intermediate variables.
  3. Final Answer:

    It allows chaining custom functions for clearer and cleaner code. -> Option C
  4. Quick Check:

    pipe + groupby = cleaner chaining [OK]
Hint: Remember: pipe helps chain functions clearly [OK]
Common Mistakes:
  • Thinking pipe sorts groups automatically
  • Assuming pipe changes data types
  • Believing pipe removes missing values
2. Which of the following is the correct syntax to use pipe after a groupby operation in pandas?
easy
A. pipe(df.groupby('col'), custom_func)
B. df.pipe(groupby('col'), custom_func)
C. df.groupby('col').pipe = custom_func()
D. df.groupby('col').pipe(custom_func)

Solution

  1. Step 1: Recall correct method chaining syntax

    In pandas, pipe is called as a method on the DataFrame or GroupBy object.
  2. Step 2: Identify correct chaining after groupby

    The correct syntax is df.groupby('col').pipe(custom_func), passing the grouped object to the function.
  3. Final Answer:

    df.groupby('col').pipe(custom_func) -> Option D
  4. Quick Check:

    Method chaining uses dot notation [OK]
Hint: Use dot notation: groupby(...).pipe(...) [OK]
Common Mistakes:
  • Trying to assign pipe like an attribute
  • Passing groupby as argument inside pipe
  • Calling pipe as a standalone function
3. Given the code below, what will be the output?
import pandas as pd
df = pd.DataFrame({'Team': ['A', 'A', 'B', 'B'], 'Points': [10, 15, 10, 20]})
def add_bonus(group):
    group['Points'] = group['Points'] + 5
    return group
result = df.groupby('Team').pipe(lambda gb: gb.apply(add_bonus))
print(result)
medium
A. Points column values increased by 5 within each group
B. Original DataFrame unchanged
C. Error because pipe cannot be used with groupby
D. Points column values doubled within each group

Solution

  1. Step 1: Understand groupby with pipe and custom function

    The pipe passes the grouped DataFrame to add_bonus, which adds 5 to 'Points' in each group.
  2. Step 2: Check the effect on the DataFrame

    Each 'Points' value is increased by 5, so values become 15, 20, 15, 25 respectively.
  3. Final Answer:

    Points column values increased by 5 within each group -> Option A
  4. Quick Check:

    pipe applies function to groups [OK]
Hint: pipe passes grouped data to your function [OK]
Common Mistakes:
  • Thinking pipe does not modify data
  • Assuming pipe causes error with groupby
  • Believing points are doubled instead of increased
4. Identify the error in the following code using groupby with pipe:
import pandas as pd
df = pd.DataFrame({'Category': ['X', 'X', 'Y'], 'Value': [1, 2, 3]})
def multiply(group):
    group['Value'] = group['Value'] * 2
result = df.groupby('Category').pipe(lambda gb: gb.apply(multiply))
print(result)
medium
A. The function multiply does not return the modified group.
B. pipe cannot be used after groupby.
C. The groupby column name is incorrect.
D. DataFrame is missing required columns.

Solution

  1. Step 1: Check the custom function used in pipe

    The function multiply modifies the group but does not return it.
  2. Step 2: Understand pipe requires function to return data

    Without returning the group, pipe receives None, causing unexpected results or errors.
  3. Final Answer:

    The function multiply does not return the modified group. -> Option A
  4. Quick Check:

    pipe needs function to return data [OK]
Hint: Always return the modified group in pipe functions [OK]
Common Mistakes:
  • Forgetting to return the group in the function
  • Thinking pipe can't follow groupby
  • Assuming column names are wrong without checking
5. You have a DataFrame with sales data for different stores and want to calculate the average sales per store, then add a column showing sales above average using groupby and pipe. Which code correctly achieves this?
hard
A. df.groupby('Store').pipe(lambda g: g['AboveAvg'] = g['Sales'] - g['Sales'].mean())
B. df.groupby('Store').pipe(lambda gb: gb.apply(lambda g: g.assign(AboveAvg=g['Sales'] > g['Sales'].mean())))
C. df.groupby('Store').pipe(lambda g: g['AboveAvg'] = g['Sales'] > g['Sales'].mean())
D. df.pipe(lambda g: g.groupby('Store').assign(AboveAvg=g['Sales'] > g['Sales'].mean()))

Solution

  1. Step 1: Understand the goal

    We want to group by 'Store', then add a column 'AboveAvg' that is True if sales are above the store's average.
  2. Step 2: Analyze each option

    df.groupby('Store').pipe(lambda gb: gb.apply(lambda g: g.assign(AboveAvg=g['Sales'] > g['Sales'].mean()))) correctly uses pipe on the grouped object and uses assign to add the column based on group mean.
    df.pipe(lambda g: g.groupby('Store').assign(AboveAvg=g['Sales'] > g['Sales'].mean())) applies assign before grouping, which is incorrect.
    Options A and C try to assign inside lambda without returning the DataFrame, causing errors.
  3. Final Answer:

    df.groupby('Store').pipe(lambda gb: gb.apply(lambda g: g.assign(AboveAvg=g['Sales'] > g['Sales'].mean()))) -> Option B
  4. Quick Check:

    Use pipe with assign inside lambda [OK]
Hint: Use assign inside pipe lambda to add columns [OK]
Common Mistakes:
  • Assigning inside lambda without returning DataFrame
  • Applying assign before groupby
  • Using assignment (=) inside lambda without returning
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