0
0
Pandasdata~5 mins

Aggregation with agg() in Pandas

Choose your learning style9 modes available
Introduction

Aggregation helps you summarize data by calculating values like sums or averages. The agg() function lets you do many summaries at once.

You want to find the average and maximum sales for each product.
You need to calculate multiple statistics like mean, sum, and count on a dataset.
You want to quickly summarize data columns with different functions.
You want to group data and apply different aggregations to each group.
You want to create a report showing key numbers from your data.
Syntax
Pandas
DataFrame.agg(func=None, axis=0, *args, **kwargs)

func can be a single function, a list of functions, or a dictionary mapping columns to functions.

You can apply different functions to different columns by passing a dictionary.

Examples
Calculate the sum of all numeric columns in the DataFrame.
Pandas
df.agg('sum')
Calculate minimum, maximum, and mean for all numeric columns.
Pandas
df.agg(['min', 'max', 'mean'])
Calculate sum of 'sales' column and mean of 'quantity' column.
Pandas
df.agg({'sales': 'sum', 'quantity': 'mean'})
Sample Program

This code creates a small table of products with sales and quantity. Then it calculates the total and average sales and quantity using agg().

Pandas
import pandas as pd

data = {
    'product': ['A', 'B', 'A', 'B'],
    'sales': [100, 200, 150, 300],
    'quantity': [1, 3, 2, 4]
}
df = pd.DataFrame(data)

# Aggregate sum and mean for sales and quantity
result = df.agg({'sales': ['sum', 'mean'], 'quantity': ['sum', 'mean']})
print(result)
OutputSuccess
Important Notes

If you use agg() on a grouped DataFrame, it applies the functions to each group separately.

You can pass your own custom functions to agg() as well.

Summary

agg() helps summarize data with one or many functions.

You can apply different functions to different columns easily.

It works well with grouped data for detailed summaries.