0
0
Pandasdata~10 mins

GroupBy with custom functions in Pandas - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to group the DataFrame by 'Category'.

Pandas
grouped = df.groupby([1])
Drag options to blanks, or click blank then click option'
A'Date'
B'Value'
C'Index'
D'Category'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a column name that does not exist in the DataFrame.
Forgetting to put the column name in quotes.
2fill in blank
medium

Complete the code to apply a custom function that calculates the range (max - min) of 'Value' in each group.

Pandas
def range_func(x):
    return x.max() - [1]

result = df.groupby('Category')['Value'].apply(range_func)
Drag options to blanks, or click blank then click option'
Amean()
Bmin()
Csum()
Dmedian()
Attempts:
3 left
💡 Hint
Common Mistakes
Using mean or sum instead of min for calculating range.
Forgetting to subtract the minimum value.
3fill in blank
hard

Fix the error in the custom function to correctly calculate the mean of 'Value' after grouping.

Pandas
def mean_func(x):
    return x.[1]()

result = df.groupby('Category')['Value'].apply(mean_func)
Drag options to blanks, or click blank then click option'
Amean
Bmedian
Csum
Dmax
Attempts:
3 left
💡 Hint
Common Mistakes
Using sum or max instead of mean.
Forgetting the parentheses after the method name.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps each group to the count of 'Value' greater than 10.

Pandas
counts = {group: sum(df.loc[df['Category'] == group, 'Value'] [1] 10) for group in df['Category'].unique() if sum(df.loc[df['Category'] == group, 'Value'] [2] 10) > 0}
Drag options to blanks, or click blank then click option'
A>
B<
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '==' instead of '>' causes wrong counts.
Using different operators in the two blanks leads to errors.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps each group to the average 'Value' for values greater than 5.

Pandas
averages = {group: df.loc[(df['Category'] == group) & (df['Value'] [1] 5), [2]].[3]() for group in df['Category'].unique()}
Drag options to blanks, or click blank then click option'
A>
B'Value'
Cmean
Dsum
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' for filtering.
Selecting the wrong column or forgetting to select a column.
Using sum instead of mean for average.