Passing a single function name applies it uniformly; passing a list computes multiple aggregations at once, each becoming its own row or column in the result; and passing a dict applies a specific, different aggregation to each named column. It's most commonly chained after groupby() to compute several distinct per-group statistics in one pass, rather than calling separate methods like .sum() and .mean() and combining their results manually afterward.
1Understanding df.agg()
Passing a single function name applies it uniformly; passing a list computes multiple aggregations at once, each becoming its own row or column in the result; and passing a dict applies a specific, different aggregation to each named column. It's most commonly chained after groupby() to compute several distinct per-group statistics in one pass, rather than calling separate methods like .sum() and .mean() and combining their results manually afterward.
Pass a dict to agg(), mapping each column name to its own list or name of aggregation functions, to compute different, specifically-tailored aggregations for different columns in one call, instead of chaining multiple separate aggregation calls and manually combining their results.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
print(df.groupby("team")["score"].agg(["sum", "mean"]))2Practical Example
Here is a real-world application of df.agg() showing how it is used in production Pandas code.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30], "age": [22, 25, 30]})
print(df.groupby("team").agg({"score": "sum", "age": "max"}))3Best Practices
Follow these guidelines when working with df.agg():
1. Use agg() with a dict to compute different, appropriately-chosen aggregations per column in one pass, rather than several separate calls
2. Chain agg() after groupby() for multi-statistic per-group summaries, instead of computing each statistic with a separate method call
3. Pass a list of functions to a single column's agg() call when you need multiple different summaries of that one column at once
Tip: Pass a dict to agg(), mapping each column name to its own list or name of aggregation functions, to compute different, specifically-tailored aggregations for different columns in one call, instead of chaining multiple separate aggregation calls and manually combining their results.
import pandas as pd
df = pd.DataFrame({"team": ["A", "A", "B"], "score": [10, 20, 30]})
print(df.groupby("team")["score"].agg(["sum", "mean"]))