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
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.
DataFrame.agg(func=None, axis=0, *args, **kwargs)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).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)
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)
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().
'sum', 'mean', 'min', 'max', 'std', or pass NumPy function references like np.mean.
Explore interactive code cells, dynamically generate classes, test type vs isinstance comparisons, and run self-validating assertions.
View on GitHubAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.