Python:Pandas .agg()

vanshNandwani6868998099's avatar
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.

  • 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

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 DataFrame
data = {
'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 aggregations
result = df.groupby('Department').agg({
'Salary': ['mean', 'max'],
'Bonus': 'sum'
})
print(result)

This example produces the following output:

Salary Bonus
mean max sum
Department
HR 42500 45000 4500
IT 72500 75000 16500
Sales 55000 60000 11000

Codebyte Example

In this example, the average Points and total Assists are computed for each Team using groupby().agg():

Code
Output
Loading...

All contributors

Contribute to 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