Multiple aggregation functions in Pandas - Time & Space Complexity
We want to understand how the time needed to run multiple aggregation functions on data grows as the data gets bigger.
How does adding more data affect the work pandas does when summarizing it?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({
'group': ['A', 'B', 'A', 'B', 'A', 'B'],
'value': [10, 20, 30, 40, 50, 60]
})
result = df.groupby('group').agg({'value': ['sum', 'mean', 'max']})
This code groups data by a column and calculates sum, mean, and max for each group.
- Primary operation: pandas loops internally over each group to compute each aggregation.
- How many times: For each group, it processes all rows once per aggregation function.
As the number of rows grows, pandas must look at more data for each aggregation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 (10 rows x 3 functions) |
| 100 | About 300 (100 rows x 3 functions) |
| 1000 | About 3000 (1000 rows x 3 functions) |
Pattern observation: The work grows roughly in direct proportion to the number of rows and the number of aggregation functions.
Time Complexity: O(n)
This means the time to run these aggregations grows linearly with the number of rows in the data.
[X] Wrong: "Adding more aggregation functions multiplies the time by the square of the data size."
[OK] Correct: Each aggregation looks at the data once, so time grows with data size times number of functions, not squared.
Knowing how aggregation time grows helps you explain performance when working with grouped data, a common task in data analysis.
"What if we added more grouping columns? How would the time complexity change?"
Practice
agg() function do when used after groupby() in pandas?Solution
Step 1: Understand groupby operation
Thegroupby()function splits data into groups based on column values.Step 2: Apply
Theagg()after groupingagg()function applies one or more aggregation functions like sum, mean, count to each group and returns the results.Final Answer:
It applies multiple aggregation functions to each group and returns their results. -> Option DQuick Check:
agg()summarizes groups [OK]
- Thinking agg() sorts data
- Confusing agg() with filtering
- Assuming agg() merges DataFrames
sum and mean aggregations on a grouped DataFrame df grouped by column 'Category'?Solution
Step 1: Identify correct method chaining
Grouping must happen first withgroupby('Category'), then aggregation withagg().Step 2: Use list of functions inside
The correct syntax uses a list of function names:agg()agg(['sum', 'mean']).Final Answer:
df.groupby('Category').agg(['sum', 'mean']) -> Option AQuick Check:
Group first, then agg with list [OK]
- Calling agg() before groupby()
- Passing multiple args instead of list to agg()
- Using aggregate() without list syntax
import pandas as pd
data = {'Team': ['A', 'A', 'B', 'B'], 'Points': [10, 15, 10, 20], 'Assists': [5, 7, 8, 6]}
df = pd.DataFrame(data)
result = df.groupby('Team').agg({'Points': ['sum', 'mean'], 'Assists': 'max'})
print(result)What is the output?
Solution
Step 1: Group by 'Team'
The data is grouped into two groups: Team A and Team B.Step 2: Apply multiple aggregations
For 'Points', sum and mean are calculated; for 'Assists', max is calculated for each group.Final Answer:
A DataFrame with sum and mean of Points and max of Assists for each Team. -> Option AQuick Check:
agg() supports dict with list and string [OK]
- Expecting error mixing list and string in agg dict
- Confusing which function applies to which column
- Thinking output is a Series, not DataFrame
df.groupby('Category').agg({'Sales': 'sum', 'Profit': ['mean', 'max']})It raises an error. Why?
Solution
Step 1: Check agg() dictionary syntax
agg() accepts a dictionary where values can be a string or list of functions per column.Step 2: Verify code correctness
The code correctly applies 'sum' to 'Sales' and ['mean', 'max'] to 'Profit' without error.Final Answer:
The code is correct and runs without error. -> Option CQuick Check:
agg() accepts mixed string and list in dict [OK]
- Thinking mixing string and list causes error
- Expecting all functions must be in a list
- Confusing agg() with apply() syntax
df with columns 'Store', 'Sales', and 'Expenses'. You want to group by 'Store' and get the total sales, average expenses, and count of sales entries per store in one step. Which code correctly does this?Solution
Step 1: Identify required aggregations per column
We want total sales (sum), average expenses (mean), and count of sales entries (count).Step 2: Map functions correctly in agg()
Use a dict: 'Sales' gets ['sum', 'count'], 'Expenses' gets 'mean'. This matches df.groupby('Store').agg({'Sales': ['sum', 'count'], 'Expenses': 'mean'}).Final Answer:
df.groupby('Store').agg({'Sales': ['sum', 'count'], 'Expenses': 'mean'}) -> Option BQuick Check:
Dict with list and string per column [OK]
- Putting count under wrong column
- Using agg() without dict for columns
- Applying all functions to all columns
Ready to prove it?
Pass the test and this pattern moves unknown
