Listen up. If you're going to process data in Python, you need to understand Advanced Aggregations in Python. This is where data engineers separate themselves from script kiddies. It's about writing code that scales.
1Pandas aggregations Part 1
A single .groupby('City').mean() gives you one statistic per group, but real reporting usually needs several at once ā the average, the total, and the maximum, all in the same pass. That's what .agg() is for. Passing a list of function names, df.groupby('Region')['Sales'].agg(['min', 'max', 'sum']), runs all three aggregations in one grouped pass and returns a DataFrame with one column per function, so you never have to run the same groupby() three separate times.
The more powerful form passes a dictionary instead of a list: df.groupby('Department').agg({'Age': 'mean', 'Salary': 'max'}) applies a *different* function to each column ā the average age per department, but the maximum salary per department, computed in a single grouped operation. This dictionary form is what makes .agg() genuinely different from just chaining .mean() and .max() separately, since it lets every column get exactly the summary statistic that's meaningful for it.
When you aggregate a single column with multiple functions (the list form), Pandas needs somewhere to put both results, so it builds a MultiIndex column header ā one level for the original column name, one level for the function applied. Reading res[('Sales', 'sum')] or flattening the columns with res.columns = ['_'.join(c) for c in res.columns] are both normal next steps once you understand why the hierarchy is there in the first place.
# Example
import pandas as pd
print("Running Pandas...")Data processed and aggregated.
2Step-by-Step Breakdown
We know how to calculate the .mean() or .sum() of a group. But what if you want to calculate the mean AND the sum AND the maximum value all at the same time?
Which Pandas method allows you to apply multiple different mathematical functions to a GroupBy object simultaneously?
- ā.multiple()
- ā.agg() (or .aggregate())
- ā.math_all()
You can pass a list of string names representing the functions you want. Pandas will return a DataFrame with a multi-level column header.
When passing a list to .agg(["mean", "sum"]), how do you format the mathematical operations?
- āAs strings representing the function names.
- āAs raw SQL code.
- āAs boolean True/False values.
The most powerful feature of .agg() is passing a dictionary. This allows you to apply different mathematical functions to DIFFERENT columns simultaneously.
If you want to calculate the "sum" of Revenue and the "mean" of Units_Sold in the same operation, what structure should you pass into .agg()?
- āA Python list of numbers.
- āA dictionary mapping columns to functions:
{'Revenue': 'sum', 'Units_Sold': 'mean'} - āTwo separate groupby statements.
Now, prepare yourself. We are about to enter the ADA Defense Protocol. Ensure you understand what happens when you use multiple metrics.
ADA DEFENSE: When you apply multiple functions to a single column like .agg(["mean", "sum"]), how does Pandas format the resulting DataFrame?
- āIt creates a MultiIndex (hierarchical) column structure to fit both metrics.
- āIt throws an error because columns can only hold one metric.
- āIt concatenates the mean and sum into a single long string.
Threat neutralized. Multi-level aggregation enabled. Your reporting capabilities are now limitless.
Threat neutralized. Concept validated. Proceed to the next section.
Apply Real Per-Column Aggregations. Finish custom_aggregation(): map different functions to different columns in one .agg() call.
Level Up š
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Flatten MultiIndex Columns for Readable Output
A MultiIndex column header like ('Sales', 'sum') is harder for downstream tools, exported CSVs, and assistive technology to interpret than a plain 'Sales_sum' label. Flatten it before publishing a report.
res.columns = ['_'.join(col).strip('_') for col in res.columns]SEO Implications
- 1
High-Intent Reference Content
Searches like 'pandas agg multiple functions', 'pandas agg dictionary', and 'pandas groupby multiindex columns' are common among people building reporting pipelines, making accurate, example-driven coverage of .agg() valuable for organic search.
Best Practices
Use Named Aggregation for Clear Column Names
Instead of a plain list (which produces a MultiIndex), use `df.groupby('City').agg(avg_sales=('Sales', 'mean'), max_sales=('Sales', 'max'))` ā Pandas' named-aggregation syntax gives you flat, self-describing column names in one step.
Prefer the Dictionary Form When Columns Need Different Metrics
Reach for `.agg({'Age': 'mean', 'Salary': 'max'})` instead of running two separate `groupby()` calls and merging the results ā it's one grouped pass instead of two, and keeps related metrics aligned by group automatically.
Frequent Bugs
Forgetting that `.agg()` with a list produces MultiIndex columns, then trying to access a column by its plain string name and getting a KeyError.
Access MultiIndex columns as tuples (e.g. `res[('Sales', 'sum')]`), or flatten the columns immediately after aggregating with `res.columns = ['_'.join(c) for c in res.columns]`.
Real-World Examples
Building a Department Summary Report
An HR analytics script needs, per department, the average age and the highest salary, in a single readable table for a dashboard.
import pandas as pd
df = pd.DataFrame({
'Department': ['Eng', 'Eng', 'Sales', 'Sales'],
'Age': [29, 41, 35, 26],
'Salary': [95000, 120000, 88000, 91000]
})
report = df.groupby('Department').agg(
avg_age=('Age', 'mean'),
max_salary=('Salary', 'max')
)