Pandas DataFrame agg() Method

import pandas as pd 

df = pd.DataFrame({'MATH': [30, 40, 50], 'ENGLISH': [20, 30, 40]})
print(df.agg(['sum', 'mean']))

Expected Output:

       MATH  ENGLISH
sum   120.0     90.0
mean   40.0     30.0

1. Overview and Syntax

The DataFrame.agg() (or aggregate()) method executes one or more reduction operations across rows or columns. It supports function names passed as strings (e.g., 'sum', 'mean'), NumPy functions, custom lambdas, or column-specific dictionary mappings.

Method Signature: DataFrame.agg(func=None, axis=0, *args, **kwargs)
Parameters:
• func: String name, list of functions, or dictionary mapping column names to functions.
• axis: 0 or 'index' (column-wise reduction), 1 or 'columns' (row-wise reduction).
Returns: Scalar, Series, or DataFrame based on aggregation complexity.

2. Multi-Metric Function Lists

Passing a list of aggregation strings calculates multiple summary statistics across numeric columns simultaneously.

import pandas as pd 

df_scores = pd.DataFrame({
    'MATH': [45, 60, 75, 90],
    'ENGLISH': [50, 55, 65, 80]
})

summary = df_scores.agg(['min', 'max', 'mean', 'std'])
print(summary)

3. Column-Specific Mapping

Using a dictionary mapping allows tailored aggregation rules per column (e.g., calculating total sales volume alongside average unit prices).

import pandas as pd 

sales_df = pd.DataFrame({
    'UNITS': [10, 20, 15, 30],
    'PRICE': [5.0, 5.0, 12.0, 12.0]
})

custom_summary = sales_df.agg({
    'UNITS': 'sum',
    'PRICE': 'mean'
})
print(custom_summary)

4. Frequently Asked Questions (FAQs)

Q: What is the main difference between apply() and agg()?
agg() is optimized specifically for data reduction operations (returning single scalar values per column), whereas apply() can return full Series or transformed DataFrames of identical size.

Q: Can custom Python functions or lambdas be used with agg()?
Yes, you can pass custom functions (e.g., df.agg(lambda x: x.max() - x.min())) directly into agg().

5. Common Errors & Troubleshooting

AttributeError: 'str' object has no attribute 'xxx'
Cause: Supplying an invalid function name string.
Fix: Use valid Pandas function aliases like 'sum', 'mean', 'min', 'max', 'std', or pass NumPy function references like np.mean.
Interactive Companion Jupyter Notebook

Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.

View on GitHub Open In Colab

6. Related Tutorials




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer