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
Step 1: Check the custom function used in pipe
The function multiply modifies the group but does not return it.
Step 2: Understand pipe requires function to return data
Without returning the group, pipe receives None, causing unexpected results or errors.
Final Answer:
The function multiply does not return the modified group. -> Option A
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
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.
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.
Final Answer:
df.groupby('Store').pipe(lambda gb: gb.apply(lambda g: g.assign(AboveAvg=g['Sales'] > g['Sales'].mean()))) -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.