Bird
Raised Fist0
Pandasdata~10 mins

Split-apply-combine mental model in Pandas - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Split-apply-combine mental model
Start with DataFrame
↓
Split data into groups
↓
Apply function to each group
↓
Combine results into new DataFrame
↓
Output
The data is split into groups, a function is applied to each group, then results are combined into one output.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({'Team': ['A', 'A', 'B', 'B'], 'Points': [10, 15, 10, 20]})
result = df.groupby('Team')['Points'].mean()
print(result)
This code groups data by 'Team', calculates average 'Points' per team, and prints the result.
Execution Table
StepActionData StateResult
1Create DataFramedf with 4 rows, columns Team and PointsDataFrame ready
2Group by 'Team'Groups: 'A' with 2 rows, 'B' with 2 rowsGroups formed
3Apply mean to 'Points' in each groupGroup A Points: [10, 15], Group B Points: [10, 20]Means: A=12.5, B=15.0
4Combine resultsSeries with index Team and mean PointsOutput Series ready
5Print resultSeries displayedTeam A 12.5 B 15.0 Name: Points, dtype: float64
💡 All groups processed and combined, output produced
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
dfNoneDataFrame with 4 rowsSame DataFrameSame DataFrameSame DataFrameSame DataFrame
groupsNoneNoneDataFrameGroupBy object with keys 'A' and 'B'Same groupsSame groupsSame groups
resultNoneNoneNoneSeries with means per groupSame SeriesSame Series
Key Moments - 3 Insights
Why do we split the data before applying the function?
Splitting groups data by a key so the function applies separately to each group, as shown in step 2 and 3 of the execution_table.
What does 'combine' mean in this model?
Combine means putting all group results back together into one structure, like the Series in step 4 and 5.
Is the original DataFrame changed after groupby?
No, the original DataFrame stays the same; groupby creates groups without modifying the original, as seen in variable_tracker for 'df'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the mean Points for group 'A' after step 3?
A12.5
B15.0
C10
D20
💡 Hint
Check the 'Apply mean' row in execution_table step 3.
At which step are the groups actually formed?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Group by' action in execution_table.
If we changed the function from mean to sum, what would change in the execution_table?
AGroups would change
BDataFrame would have more rows
CStep 3 result values would be sums instead of means
DNo change at all
💡 Hint
Focus on the 'Apply function' step in execution_table.
Concept Snapshot
Split-apply-combine model:
1. Split data into groups by key
2. Apply function to each group separately
3. Combine results into one output
Use pandas groupby() to do this easily
Example: df.groupby('key')['value'].mean()
Full Transcript
The split-apply-combine model means we start with a DataFrame, split it into groups by a key column, apply a function like mean to each group, then combine the results into a new output. In the example, we group by 'Team', calculate average 'Points' per team, and get a Series with these averages. The original DataFrame stays unchanged. This model helps analyze data by groups simply and clearly.

Practice

(1/5)
1. What is the main idea behind the split-apply-combine mental model in pandas?
easy
A. Create new columns, rename them, then delete old columns
B. Sort data, filter rows, then plot results
C. Split data into groups, apply a function to each group, then combine results
D. Load data, clean missing values, then save to file

Solution

  1. Step 1: Understand the split step

    The data is divided into groups based on some criteria using groupby().
  2. Step 2: Apply and combine steps

    A function is applied to each group separately, then the results are combined into a new DataFrame.
  3. Final Answer:

    Split data into groups, apply a function to each group, then combine results -> Option C
  4. Quick Check:

    Split-apply-combine = Group, apply, combine [OK]
Hint: Remember: split groups, apply function, combine results [OK]
Common Mistakes:
  • Confusing split-apply-combine with sorting or filtering
  • Thinking it only applies to plotting or saving files
  • Mixing up the order of steps
2. Which of the following is the correct syntax to group a DataFrame df by the column 'Category' and calculate the mean of each group?
easy
A. df.groupby('Category').mean()
B. df.mean().groupby('Category')
C. df.groupby.mean('Category')
D. df.groupby('Category').apply(mean)

Solution

  1. Step 1: Identify correct groupby syntax

    The correct way to group by a column is df.groupby('Category').
  2. Step 2: Apply aggregation function

    To get the mean of each group, use .mean() after grouping.
  3. Final Answer:

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

    Groupby then mean = df.groupby('Category').mean() [OK]
Hint: Use df.groupby('col').mean() to get group means [OK]
Common Mistakes:
  • Calling mean before groupby
  • Using apply(mean) without importing mean function
  • Wrong method chaining order
3. Given the DataFrame 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()?
medium
A. Category as column with sums: A=5, B=3, C=4
B. Error because sum() cannot be applied
C. Sum of all values ignoring groups: 21
D. Category as index with sums: A=12, B=5, C=4

Solution

  1. Step 1: Group data by 'Category'

    Rows are grouped by 'Category': A, B, and C groups.
  2. Step 2: Sum values in each group

    Sum values for A: 5+7=12, B: 3+2=5, C: 4.
  3. Final Answer:

    Category as index with sums: A=12, B=5, C=4 -> Option D
  4. Quick Check:

    Sum per group = A:12, B:5, C:4 [OK]
Hint: Sum values after groupby to get totals per group [OK]
Common Mistakes:
  • Summing all values ignoring groups
  • Expecting category as a column instead of index
  • Thinking sum() causes error
4. Consider this code snippet:
result = df.groupby('Type').agg({'Score': 'mean', 'Age': 'max'})

What is wrong if the code raises a KeyError?
medium
A. The aggregation functions 'mean' and 'max' are invalid
B. The DataFrame does not have a column named 'Type'
C. The groupby method cannot take a string argument
D. agg() requires a list, not a dictionary

Solution

  1. Step 1: Understand KeyError cause

    A KeyError usually means the column used for grouping does not exist in the DataFrame.
  2. Step 2: Check groupby argument and agg usage

    Using a string in groupby and a dictionary in agg is correct syntax.
  3. Final Answer:

    The DataFrame does not have a column named 'Type' -> Option B
  4. Quick Check:

    KeyError means missing column [OK]
Hint: Check column names before groupby to avoid KeyError [OK]
Common Mistakes:
  • Assuming aggregation functions are invalid
  • Thinking groupby can't take string columns
  • Misunderstanding agg() argument types
5. You have a DataFrame 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?
hard
A. df.groupby('Team').apply(lambda g: g[g['Points'] == g['Points'].max()])
B. df.groupby('Team')['Points'].max()
C. df.groupby('Player')['Points'].sum()
D. df.groupby('Team').mean()['Points']

Solution

  1. Step 1: Understand the goal

    We want the player with the highest points per team, not just the max points value.
  2. Step 2: Use groupby and apply to filter rows

    Using apply with a lambda filters each group to rows where 'Points' equals the group's max.
  3. 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.
  4. Final Answer:

    df.groupby('Team').apply(lambda g: g[g['Points'] == g['Points'].max()]) -> Option A
  5. Quick Check:

    Use apply with filter to get max player per group [OK]
Hint: Use groupby + apply with filter to get max per group row [OK]
Common Mistakes:
  • Using max() alone returns only values, not rows
  • Grouping by wrong column
  • Using mean() instead of max()
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