Split-apply-combine mental model in Pandas - Time & Space Complexity
When using pandas to group data and then apply calculations, it is important to understand how the time needed grows as the data gets bigger.
We want to know how the time changes when we split data into groups, do work on each group, and then combine the results.
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B', 'C', 'A'],
'Value': [10, 20, 30, 40, 50, 60]
})
grouped = df.groupby('Category')
result = grouped['Value'].sum()
This code splits the data by 'Category', sums the 'Value' in each group, and combines the sums into a result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Going through each row to assign it to a group.
- How many times: Once for each row in the data (n times).
- Secondary operation: Summing values inside each group, which depends on group size.
As the number of rows grows, the time to split and sum grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to assign groups + sum within groups |
| 100 | About 100 steps to assign groups + sum within groups |
| 1000 | About 1000 steps to assign groups + sum within groups |
Pattern observation: The total work grows roughly in a straight line as the data size increases.
Time Complexity: O(n)
This means the time needed grows roughly in direct proportion to the number of rows in the data.
[X] Wrong: "Grouping data is instant and does not depend on data size."
[OK] Correct: Grouping requires looking at every row to decide its group, so it takes more time as data grows.
Understanding how grouping and applying functions scale helps you explain your code choices clearly and shows you know how data size affects performance.
"What if we applied a more complex function instead of sum, like sorting each group? How would the time complexity change?"
Practice
split-apply-combine mental model in pandas?Solution
Step 1: Understand the split step
The data is divided into groups based on some criteria usinggroupby().Step 2: Apply and combine steps
A function is applied to each group separately, then the results are combined into a new DataFrame.Final Answer:
Split data into groups, apply a function to each group, then combine results -> Option CQuick Check:
Split-apply-combine = Group, apply, combine [OK]
- Confusing split-apply-combine with sorting or filtering
- Thinking it only applies to plotting or saving files
- Mixing up the order of steps
df by the column 'Category' and calculate the mean of each group?Solution
Step 1: Identify correct groupby syntax
The correct way to group by a column isdf.groupby('Category').Step 2: Apply aggregation function
To get the mean of each group, use.mean()after grouping.Final Answer:
df.groupby('Category').mean() -> Option AQuick Check:
Groupby then mean = df.groupby('Category').mean() [OK]
- Calling mean before groupby
- Using apply(mean) without importing mean function
- Wrong method chaining order
df below:Category Value 0 A 5 1 B 3 2 A 7 3 B 2 4 C 4
What is the output of
df.groupby('Category').sum()?Solution
Step 1: Group data by 'Category'
Rows are grouped by 'Category': A, B, and C groups.Step 2: Sum values in each group
Sum values for A: 5+7=12, B: 3+2=5, C: 4.Final Answer:
Category as index with sums: A=12, B=5, C=4 -> Option DQuick Check:
Sum per group = A:12, B:5, C:4 [OK]
- Summing all values ignoring groups
- Expecting category as a column instead of index
- Thinking sum() causes error
result = df.groupby('Type').agg({'Score': 'mean', 'Age': 'max'})What is wrong if the code raises a KeyError?
Solution
Step 1: Understand KeyError cause
A KeyError usually means the column used for grouping does not exist in the DataFrame.Step 2: Check groupby argument and agg usage
Using a string in groupby and a dictionary in agg is correct syntax.Final Answer:
The DataFrame does not have a column named 'Type' -> Option BQuick Check:
KeyError means missing column [OK]
- Assuming aggregation functions are invalid
- Thinking groupby can't take string columns
- Misunderstanding agg() argument types
df with columns 'Team', 'Player', and 'Points'. You want to find the player with the highest points in each team. Which code correctly uses the split-apply-combine model to achieve this?Solution
Step 1: Understand the goal
We want the player with the highest points per team, not just the max points value.Step 2: Use groupby and apply to filter rows
Usingapplywith a lambda filters each group to rows where 'Points' equals the group's max.Step 3: Check other options
df.groupby('Team')['Points'].max() returns max points per team but not the player. df.groupby('Player')['Points'].sum() groups by player, not team. df.groupby('Team').mean()['Points'] returns mean points, not max player.Final Answer:
df.groupby('Team').apply(lambda g: g[g['Points'] == g['Points'].max()]) -> Option AQuick Check:
Use apply with filter to get max player per group [OK]
- Using max() alone returns only values, not rows
- Grouping by wrong column
- Using mean() instead of max()
Ready to prove it?
Pass the test and this pattern moves unknown
