Bird
Raised Fist0
Pandasdata~20 mins

groupby() basics in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Groupby Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of groupby sum aggregation
What is the output of this code?
import pandas as pd

data = {'Team': ['A', 'A', 'B', 'B', 'C'], 'Points': [10, 15, 10, 5, 20]}
df = pd.DataFrame(data)
result = df.groupby('Team').sum()
Pandas
import pandas as pd

data = {'Team': ['A', 'A', 'B', 'B', 'C'], 'Points': [10, 15, 10, 5, 20]}
df = pd.DataFrame(data)
result = df.groupby('Team').sum()
print(result)
A
  Team  Points
0    A      25
1    B      15
2    C      20
B
       Points
Team          
A          25
B          15
C          20
C
Team
A    25
B    15
C    20
Name: Points, dtype: int64
D
       Points
Team          
A          10
B          10
C          20
Attempts:
2 left
💡 Hint
Remember groupby groups rows by the 'Team' column and sums the 'Points' for each group.
❓ data_output
intermediate
1:30remaining
Number of groups created by groupby
Given this DataFrame, how many groups will be created by grouping on 'Category' column?
import pandas as pd

data = {'Category': ['X', 'Y', 'X', 'Z', 'Y', 'Z', 'Z'], 'Value': [1, 2, 3, 4, 5, 6, 7]}
df = pd.DataFrame(data)
groups = df.groupby('Category')
Pandas
import pandas as pd

data = {'Category': ['X', 'Y', 'X', 'Z', 'Y', 'Z', 'Z'], 'Value': [1, 2, 3, 4, 5, 6, 7]}
df = pd.DataFrame(data)
groups = df.groupby('Category')
print(len(groups))
A3
B7
C4
D2
Attempts:
2 left
💡 Hint
Count unique values in the 'Category' column.
🔧 Debug
advanced
1:30remaining
Identify the error in groupby usage
What error does this code raise?
import pandas as pd

data = {'Name': ['Anna', 'Bob', 'Cara'], 'Score': [90, 80, 85]}
df = pd.DataFrame(data)
result = df.groupby('Age').mean()
Pandas
import pandas as pd

data = {'Name': ['Anna', 'Bob', 'Cara'], 'Score': [90, 80, 85]}
df = pd.DataFrame(data)
result = df.groupby('Age').mean()
ATypeError: unsupported operand type(s) for +: 'int' and 'str'
BValueError: No numeric types to aggregate
CKeyError: 'Age'
DAttributeError: 'DataFrame' object has no attribute 'mean'
Attempts:
2 left
💡 Hint
Check if the column used in groupby exists in the DataFrame.
🚀 Application
advanced
2:00remaining
Calculate average sales per region
You have sales data:
import pandas as pd

data = {'Region': ['North', 'South', 'North', 'East', 'South', 'East'], 'Sales': [100, 200, 150, 300, 250, 350]}
df = pd.DataFrame(data)

Which code correctly calculates the average sales per region?
Pandas
import pandas as pd

data = {'Region': ['North', 'South', 'North', 'East', 'South', 'East'], 'Sales': [100, 200, 150, 300, 250, 350]}
df = pd.DataFrame(data)
Adf.groupby('Region').count()['Sales']
Bdf.groupby('Sales')['Region'].mean()
Cdf.groupby('Region').sum()['Sales'] / df['Sales'].count()
Ddf.groupby('Region')['Sales'].mean()
Attempts:
2 left
💡 Hint
Group by 'Region' and then calculate mean of 'Sales'.
🧠 Conceptual
expert
1:30remaining
Understanding groupby object behavior
Which statement about a pandas groupby object is TRUE?
AA groupby object is an iterable that yields (group_name, DataFrame) pairs.
BA groupby object immediately computes aggregation when created.
CA groupby object can be indexed like a DataFrame to get groups directly.
DA groupby object stores the original DataFrame as a list of groups.
Attempts:
2 left
💡 Hint
Think about what happens when you loop over a groupby object.

Practice

(1/5)
1. What does the groupby() function do in pandas?
easy
A. It splits the data into groups based on column values.
B. It sorts the data in ascending order.
C. It removes duplicate rows from the data.
D. It changes the data type of columns.

Solution

  1. Step 1: Understand the purpose of groupby()

    The groupby() function is used to split data into groups based on the values in one or more columns.
  2. Step 2: Compare with other options

    Sorting, removing duplicates, and changing data types are different operations and not what groupby() does.
  3. Final Answer:

    It splits the data into groups based on column values. -> Option A
  4. Quick Check:

    groupby() = split data into groups [OK]
Hint: Remember: groupby splits data by column values [OK]
Common Mistakes:
  • Confusing groupby with sorting
  • Thinking groupby removes duplicates
  • Assuming groupby changes data types
2. Which of the following is the correct syntax to group a DataFrame df by the column 'Category'?
easy
A. df.group_by('Category')
B. df.groupby['Category']
C. df.groupby('Category')
D. df.groupby(Category)

Solution

  1. Step 1: Recall the correct method name and syntax

    The correct method is groupby() called with parentheses and the column name as a string argument.
  2. Step 2: Check each option

    df.groupby('Category') uses df.groupby('Category') which is correct. df.group_by('Category') uses wrong method name group_by. df.groupby['Category'] uses square brackets instead of parentheses. df.groupby(Category) misses quotes around the column name.
  3. Final Answer:

    df.groupby('Category') -> Option C
  4. Quick Check:

    Correct syntax uses parentheses and string column name [OK]
Hint: Use df.groupby('column_name') with parentheses and quotes [OK]
Common Mistakes:
  • Using wrong method name like group_by
  • Using square brackets instead of parentheses
  • Not quoting the column name string
3. Given the DataFrame:
import pandas as pd
data = {'Team': ['A', 'A', 'B', 'B', 'C'], 'Points': [10, 15, 10, 5, 20]}
df = pd.DataFrame(data)
result = df.groupby('Team').sum()

What is the output of result?
medium
A. Team Points A 25 B 15 C 20
B. {'Team': ['A', 'B', 'C'], 'Points': [25, 15, 20]}
C. Team Points A 10 B 10 C 20
D. Team Points A 15 B 5 C 20

Solution

  1. Step 1: Group data by 'Team'

    The groups are: A with points 10 and 15, B with points 10 and 5, C with points 20.
  2. Step 2: Sum points in each group

    Sum for A = 10 + 15 = 25, B = 10 + 5 = 15, C = 20.
  3. Final Answer:

    Team Points A 25 B 15 C 20 -> Option A
  4. Quick Check:

    Sum points per team = 25, 15, 20 [OK]
Hint: Sum points after groupby to get totals per group [OK]
Common Mistakes:
  • Not summing points, just taking first value
  • Mixing up group sums
  • Confusing output format
4. What is wrong with this code snippet?
df = pd.DataFrame({'City': ['X', 'Y', 'X'], 'Sales': [100, 200, 150]})
result = df.groupby.City.sum()
medium
A. DataFrame is missing import statement.
B. The column name 'City' is misspelled.
C. The sum() function cannot be used after groupby.
D. You cannot use dot notation after groupby; it should be parentheses.

Solution

  1. Step 1: Check groupby syntax

    The correct way to group by a column is df.groupby('City') with parentheses and quotes.
  2. Step 2: Identify the error in dot notation

    Using dot notation like df.groupby.City is invalid because groupby is a method, not an attribute.
  3. Final Answer:

    You cannot use dot notation after groupby; it should be parentheses. -> Option D
  4. Quick Check:

    Use parentheses with groupby, not dot notation [OK]
Hint: Always use parentheses with groupby, not dot notation [OK]
Common Mistakes:
  • Using dot notation instead of parentheses
  • Misspelling column names
  • Thinking sum() is invalid after groupby
5. You have a sales DataFrame:
import pandas as pd
data = {'Store': ['A', 'A', 'B', 'B', 'B'], 'Product': ['X', 'Y', 'X', 'Y', 'X'], 'Sales': [100, 150, 200, 250, 300]}
df = pd.DataFrame(data)

How do you find the total sales for each store and product combination?
hard
A. df.groupby('Product').sum('Store')
B. df.groupby(['Store', 'Product']).sum()
C. df.groupby('Store').sum('Product')
D. df.groupby(['Store']).sum(['Product'])

Solution

  1. Step 1: Understand grouping by multiple columns

    To group by both 'Store' and 'Product', pass a list of column names to groupby().
  2. Step 2: Use sum() to aggregate sales

    After grouping, use sum() to add sales values for each group.
  3. Final Answer:

    df.groupby(['Store', 'Product']).sum() -> Option B
  4. Quick Check:

    Group by multiple columns using list, then sum [OK]
Hint: Group by list of columns for multi-level grouping [OK]
Common Mistakes:
  • Passing column names to sum() instead of groupby()
  • Grouping by single column only
  • Using wrong syntax for groupby
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