Python:Pandas .agg()
Published Oct 15, 2025
Contribute to Docs
The .agg() method in Pandas is used with groupby() to apply one or more aggregation functions (like sum, mean, count, etc.) to grouped data. It allows flexible and powerful summarization of DataFrame data after grouping.
Syntax
DataFrameGroupBy.agg(arg, *args, **kwargs)
Parameters:
arg: Function, string, list, or dictionary specifying the aggregation(s) to apply. Examples:'sum','mean',['min', 'max'], or{'col1': 'sum', 'col2': 'mean'}*args: Additional positional arguments passed to the function.**kwargs: Additional keyword arguments passed to the function.
Return Value:
Returns a DataFrame or Series with the aggregated results for each group.
Example
In this example, the mean Salary, maximum Salary, and total Bonus are calculated for each Department using groupby().agg():
import pandas as pd# Sample DataFramedata = {'Department': ['Sales', 'Sales', 'HR', 'HR', 'IT', 'IT'],'Salary': [50000, 60000, 40000, 45000, 70000, 75000],'Bonus': [5000, 6000, 2000, 2500, 8000, 8500]}df = pd.DataFrame(data)# Group by Department and calculate multiple aggregationsresult = df.groupby('Department').agg({'Salary': ['mean', 'max'],'Bonus': 'sum'})print(result)
This example produces the following output:
Salary Bonusmean max sumDepartmentHR 42500 45000 4500IT 72500 75000 16500Sales 55000 60000 11000
Codebyte Example
In this example, the average Points and total Assists are computed for each Team using groupby().agg():
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:Pandas on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours