Bird
Raised Fist0
Data Analysis Pythondata~20 mins

groupby() basics in Data Analysis Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Groupby Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of groupby() with sum aggregation
What is the output of this code snippet?
Data Analysis Python
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
       Points
Team          
A          15
B          5
C          20
B
       Points
Team          
A          10
B          10
C          20
C
       Points
Team          
A          25
B          15
C          20
D
       Points
Team          
A          25
B          10
C          20
Attempts:
2 left
💡 Hint
Sum adds all points for each team.
❓ data_output
intermediate
1:30remaining
Number of groups created by groupby()
How many groups are created by this groupby operation?
Data Analysis Python
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))
A7
B3
C2
D4
Attempts:
2 left
💡 Hint
Count unique categories in 'Category' column.
🔧 Debug
advanced
2:00remaining
Error raised by incorrect groupby syntax
What error does this code raise?
Data Analysis Python
import pandas as pd

data = {'Type': ['A', 'B', 'A'], 'Score': [5, 10, 15]}
df = pd.DataFrame(data)
result = df.groupby('Type', as_index=False).mean()
print(result)

# Now this incorrect code:
result2 = df.groupby(Type).sum()
ANameError: name 'Type' is not defined
BTypeError: groupby() got an unexpected keyword argument 'Type'
CAttributeError: 'DataFrame' object has no attribute 'Type'
DNo error, prints sum grouped by 'Type'
Attempts:
2 left
💡 Hint
Check if 'Type' is quoted or not in groupby argument.
🚀 Application
advanced
2:00remaining
Using groupby() to find max value per group
Which option correctly finds the maximum 'Sales' value for each 'Region'?
Data Analysis Python
import pandas as pd

data = {'Region': ['East', 'West', 'East', 'West', 'North'], 'Sales': [200, 150, 300, 100, 250]}
df = pd.DataFrame(data)
Adf.groupby('Region')['Sales'].max()
Bdf.groupby('Sales')['Region'].max()
Cdf.groupby('Region').max('Sales')
Ddf.groupby('Region').max()
Attempts:
2 left
💡 Hint
Group by 'Region' and select 'Sales' column before max.
🧠 Conceptual
expert
2:30remaining
Understanding groupby() with multiple aggregation functions
Given this code, what is the shape (rows, columns) of the resulting DataFrame?
Data Analysis Python
import pandas as pd

data = {'Category': ['A', 'A', 'B', 'B', 'C'], 'Value': [1, 2, 3, 4, 5]}
df = pd.DataFrame(data)
result = df.groupby('Category').agg(['min', 'max'])
A(5, 2)
B(5, 1)
C(3, 1)
D(3, 2)
Attempts:
2 left
💡 Hint
Count unique groups and number of aggregation functions.

Practice

(1/5)
1. What does the groupby() function do in pandas?
easy
A. It splits 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 the main function of groupby().
  3. Final Answer:

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

    groupby() = split data by column [OK]
Hint: Remember: groupby splits data into groups by column values [OK]
Common Mistakes:
  • Confusing groupby with sorting or filtering
  • Thinking groupby changes data types
  • Assuming groupby removes duplicates
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 correct method syntax

    The correct method name is groupby without underscore, called with parentheses and column name as a string.
  2. Step 2: Check each option

    The correct syntax is df.groupby('Category'). Incorrect versions include df.group_by('Category') (wrong method name), df.groupby['Category'] (wrong brackets), and df.groupby(Category) (missing quotes).
  3. Final Answer:

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

    Correct syntax uses parentheses and quotes [OK]
Hint: Use df.groupby('column_name') with quotes and parentheses [OK]
Common Mistakes:
  • Using underscore in groupby (group_by)
  • Using square brackets instead of parentheses
  • Not quoting the column name
3. Given the DataFrame df below, what is the output of df.groupby('Team')['Points'].sum()?
   Team  Points
0  A     10
1  B     15
2  A     5
3  B     10
4  C     7
medium
A. Team A 20 B 25 C 7 Name: Points, dtype: int64
B. Team A 10 B 15 C 7 Name: Points, dtype: int64
C. Team A 15 B 25 C 7 Name: Points, dtype: int64
D. Team A 5 B 10 C 7 Name: Points, dtype: int64

Solution

  1. Step 1: Group data by 'Team'

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

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

    Team A 15 B 25 C 7 Name: Points, dtype: int64 -> Option C
  4. Quick Check:

    Sum points per team = 15, 25, 7 [OK]
Hint: Add values in each group to get sum quickly [OK]
Common Mistakes:
  • Not summing all values per group
  • Mixing group labels and sums
  • Using count instead of sum
4. What is wrong with this code snippet?
grouped = df.groupby('Category')
result = grouped.sum['Sales']
print(result)
medium
A. Using square brackets instead of parentheses after sum.
B. Missing quotes around 'Category' in groupby.
C. Calling sum() without parentheses.
D. Using print() incorrectly.

Solution

  1. Step 1: Check method call syntax

    The sum function must be called with parentheses: sum(), not accessed with square brackets.
  2. Step 2: Verify other parts

    The groupby column is correctly quoted, and print usage is correct.
  3. Final Answer:

    Using square brackets instead of parentheses after sum. -> Option A
  4. Quick Check:

    sum() needs parentheses, not brackets [OK]
Hint: Call aggregation functions with parentheses like sum() [OK]
Common Mistakes:
  • Using brackets instead of parentheses for functions
  • Forgetting parentheses after sum
  • Misquoting column names
5. You have a DataFrame df with columns 'City', 'Category', and 'Sales'. How do you find the average sales for each city and category combination?
hard
A. df.groupby('City' & 'Category')['Sales'].mean()
B. df.groupby('City', 'Category')['Sales'].mean()
C. df.groupby('City' + 'Category')['Sales'].mean()
D. df.groupby(['City', 'Category'])['Sales'].mean()

Solution

  1. Step 1: Group by multiple columns

    To group by both 'City' and 'Category', pass a list of column names: ['City', 'Category'].
  2. Step 2: Calculate mean of 'Sales'

    After grouping, select 'Sales' column and apply mean() to get average sales per group.
  3. Final Answer:

    df.groupby(['City', 'Category'])['Sales'].mean() -> Option D
  4. Quick Check:

    Group by list of columns, then mean() [OK]
Hint: Group by list of columns: df.groupby(['col1','col2']) [OK]
Common Mistakes:
  • Passing multiple columns as separate arguments
  • Using bitwise AND (&) instead of list
  • Using string concatenation (+ ) instead of list
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