Pivot with aggregation functions in Pandas - Time & Space Complexity
We want to understand how the time needed to create a pivot table with aggregation changes as the data grows.
How does the work increase when we have more rows or categories?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'Category': ['A', 'B', 'A', 'B', 'C'],
'Value': [10, 20, 30, 40, 50]
})
pivot = df.pivot_table(index='Category', values='Value', aggfunc='sum')
This code creates a pivot table that sums values for each category.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Grouping rows by category and summing values.
- How many times: Each row is visited once to assign it to a group, then each group is aggregated.
As the number of rows grows, the time to group and sum grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits to rows and sums |
| 100 | About 100 visits to rows and sums |
| 1000 | About 1000 visits to rows and sums |
Pattern observation: The work grows roughly in a straight line as data size increases.
Time Complexity: O(n)
This means the time to create the pivot grows directly with the number of rows.
[X] Wrong: "Pivot tables take the same time no matter how many rows there are."
[OK] Correct: The pivot must look at each row to group and sum, so more rows mean more work.
Understanding how grouping and aggregation scale helps you explain data processing steps clearly and confidently.
"What if we added multiple aggregation functions instead of just one? How would the time complexity change?"
Practice
pivot_table function in pandas primarily do?Solution
Step 1: Understand the purpose of pivot_table
Thepivot_tablefunction rearranges data by creating a new table that summarizes data values grouped by specified keys.Step 2: Recognize aggregation role
It uses aggregation functions like sum or mean to combine data values in the new table.Final Answer:
It rearranges data to summarize and compare values using aggregation. -> Option AQuick Check:
pivot_table = rearrange + aggregate [OK]
- Confusing pivot_table with sorting or filtering
- Thinking it deletes duplicates
- Believing it converts DataFrame to list
Solution
Step 1: Identify correct function and parameters
The correct function ispd.pivot_tablewith parameters:data,index='Region',values='Sales', andaggfunc='mean'.Step 2: Check each option
pd.pivot_table(data, index='Region', values='Sales', aggfunc='mean') matches the correct syntax. pd.pivot(data, index='Region', values='Sales', aggfunc='mean') usespd.pivotwhich does not supportaggfunc. data.pivot_table('Sales', 'Region', aggfunc='mean') has wrong method call syntax. pd.pivot_table(data, columns='Region', values='Sales', aggfunc='sum') usescolumnsinstead ofindexand wrong aggregation.Final Answer:
pd.pivot_table(data, index='Region', values='Sales', aggfunc='mean') -> Option BQuick Check:
pivot_table + index + values + aggfunc = correct syntax [OK]
- Using pd.pivot instead of pd.pivot_table
- Mixing columns and index parameters
- Incorrect method call on DataFrame
import pandas as pd
data = pd.DataFrame({
'City': ['A', 'A', 'B', 'B'],
'Category': ['X', 'Y', 'X', 'Y'],
'Value': [10, 20, 30, 40]
})
pivot = pd.pivot_table(data, index='City', columns='Category', values='Value', aggfunc='sum')What is the output of
pivot?Solution
Step 1: Group data by 'City' and 'Category'
For City 'A' and Category 'X', value is 10; for 'A' and 'Y', value is 20. For City 'B' and Category 'X', value is 30; for 'B' and 'Y', value is 40.Step 2: Apply sum aggregation
Since each group has one value, sum is the same as the value itself.Final Answer:
Category X Y City A 10 20 B 30 40 -> Option CQuick Check:
Sum per group matches values [OK]
- Swapping values for categories
- Mixing up rows and columns
- Using mean instead of sum
import pandas as pd
data = pd.DataFrame({
'Team': ['A', 'A', 'B', 'B'],
'Points': [5, 10, 15, 20]
})
pivot = pd.pivot_table(data, index='Team', values='Points', aggfunc='count')
print(pivot)What is the error or issue in this code?
Solution
Step 1: Understand aggfunc='count'
The 'count' aggregation counts non-null entries in 'Points' for each 'Team'.Step 2: Check code correctness
The code is valid and will output the count of 'Points' per team without error.Final Answer:
No error; output shows count of points per team. -> Option AQuick Check:
aggfunc='count' counts entries correctly [OK]
- Thinking 'count' is invalid aggfunc
- Expecting columns parameter is mandatory
- Confusing count with sum
Solution
Step 1: Create pivot table by Store and Month
Usepivot_tablewithindex='Store',columns='Month',values='Revenue', andaggfunc='sum'to get total revenue per store per month.Step 2: Filter months by total revenue
Since filtering by months with revenue > 1000 is needed, filter columns after pivot since columns represent months.Step 3: Choose correct approach
Create pivot with index='Store', columns='Month', values='Revenue', aggfunc='sum', then filter columns with sum > 1000, which creates the pivot and then filters columns (months) where total revenue exceeds 1000, matching the requirement.Final Answer:
Create pivot with index='Store', columns='Month', values='Revenue', aggfunc='sum', then filter columns with sum > 1000. -> Option DQuick Check:
Pivot then filter sums > 1000 [OK]
- Filtering raw data before pivot loses aggregation
- Using mean instead of sum for totals
- Mixing up index and columns parameters
Ready to prove it?
Pass the test and this pattern moves unknown
