Aggregation-based features in Data Analysis Python - Time & Space Complexity
When creating aggregation-based features, we combine data by groups to get summaries like sums or averages.
We want to know how the time to do this grows as the data gets bigger.
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'user_id': [1, 2, 1, 3, 2, 1],
'purchase_amount': [100, 200, 150, 300, 250, 50]
})
agg_features = df.groupby('user_id')['purchase_amount'].sum().reset_index()
This code groups data by user_id and sums the purchase_amount for each user.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Grouping rows by user_id and summing purchase_amount values.
- How many times: Each row is visited once to assign it to a group, then each group is processed to sum values.
As the number of rows grows, the time to group and sum grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits to rows plus grouping steps |
| 100 | About 100 visits to rows plus grouping steps |
| 1000 | About 1000 visits to rows plus grouping steps |
Pattern observation: The work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to create aggregation features grows linearly with the number of data rows.
[X] Wrong: "Grouping and summing takes the same time no matter how many rows there are."
[OK] Correct: More rows mean more data to process, so the time grows as the data grows.
Understanding how aggregation scales helps you explain data processing steps clearly and shows you can think about efficiency.
"What if we added a nested loop to compute pairwise differences within each group? How would the time complexity change?"
Practice
Solution
Step 1: Understand aggregation-based features
Aggregation-based features summarize data by groups using functions like sum, mean, or count.Step 2: Compare with other options
Visualization, cleaning, and splitting data are different tasks not related to aggregation features.Final Answer:
To summarize data by groups using functions like sum or mean -> Option AQuick Check:
Aggregation = summary by groups [OK]
- Confusing aggregation with visualization
- Thinking aggregation cleans data
- Mixing aggregation with data splitting
'sales' grouped by 'region' in pandas?Solution
Step 1: Identify correct groupby syntax
The correct syntax groups by 'region' then selects 'sales' column and applies mean: df.groupby('region')['sales'].mean()Step 2: Check incorrect options
df.mean('sales').groupby('region') reverses order, df['sales'].groupby('region').mean() tries to group on a column series, df.groupby('sales')['region'].mean() groups by 'sales' instead of 'region'.Final Answer:
df.groupby('region')['sales'].mean() -> Option CQuick Check:
Group by region, then mean sales [OK]
- Calling mean before groupby
- Grouping on wrong column
- Applying groupby on a Series instead of DataFrame
import pandas as pd
data = {'team': ['A', 'A', 'B', 'B', 'B'], 'points': [10, 15, 10, 5, 20]}
df = pd.DataFrame(data)
result = df.groupby('team').agg({'points': 'sum'})
print(result)What is the output?
Solution
Step 1: Group data by 'team'
Teams are 'A' and 'B'. 'A' has points 10 and 15, 'B' has 10, 5, and 20.Step 2: Sum points per team
Sum for 'A' = 10 + 15 = 25; Sum for 'B' = 10 + 5 + 20 = 35.Final Answer:
team A 25 B 35 -> Option DQuick Check:
Sum points by team = 25 and 35 [OK]
- Adding only first value per group
- Confusing sum with mean
- Misreading group labels
'score' per 'class' in pandas?df.groupby('class').score.agg('average')Solution
Step 1: Check aggregation function name
'average' is not a valid pandas aggregation function; the correct function for average is 'mean'.Step 2: Verify other parts
Grouping by 'class' and accessing 'score' column is correct syntax; double brackets are optional here.Final Answer:
The aggregation function name 'average' is invalid; should be 'mean' -> Option BQuick Check:
Use 'mean' not 'average' for average calculation [OK]
- Using 'average' instead of 'mean'
- Thinking double brackets are mandatory
- Assuming code runs without error
'store', 'product', and 'revenue'. You want to create a new feature showing the average revenue per store and product combined. Which pandas code correctly creates this aggregation-based feature and adds it as a new column 'avg_rev' to the original DataFrame?Solution
Step 1: Understand the goal
We want average revenue per store and product, and add it as a new column matching original rows.Step 2: Use groupby with transform
Using groupby on ['store', 'product'] and transform('mean') returns a Series aligned with original DataFrame, perfect for new column.Step 3: Check other options
df['avg_rev'] = df.groupby('store')['revenue'].mean() groups only by store, not product; df['avg_rev'] = df.groupby('product')['revenue'].sum() sums revenue, not average; df['avg_rev'] = df.groupby(['store', 'product']).agg({'revenue': 'mean'}) returns a DataFrame, not a Series aligned for assignment.Final Answer:
df['avg_rev'] = df.groupby(['store', 'product'])['revenue'].transform('mean') -> Option AQuick Check:
Use transform to add group average as new column [OK]
- Using agg() which returns DataFrame, not Series
- Grouping by only one column instead of both
- Using sum instead of mean
Ready to prove it?
Pass the test and this pattern moves unknown
