Column summaries
You need totals, extrema, or averages for every column in one operation.
Pandas · Module
DataFrame.agg applies one or more aggregation operations over a selected axis. It supports single operations, lists of operations, per-column dictionaries, and named aggregations.
DataFrame.agg applies one or more aggregation operations along a chosen axis. Pass a callable or operation name, a list for multiple operations, or a dictionary to specify operations by column; additional positional and keyword arguments are forwarded to the aggregation function.
DataFrame.agg(func=None, axis=0, *args, **kwargs)| Name | Type | Description |
|---|---|---|
func | function, str, list or dict | Function, string, list, or dictionary specifying the operation or operations used for aggregation. |
axis | {0 or ‘index’, 1 or ‘columns’}, default 0 | Axis over which to aggregate: 0 or index for columns, or 1 or columns for rows. Defaults to 0. |
*args | tuple | Additional positional arguments passed to the aggregation function. |
**kwargs | dict | Additional keyword arguments passed to the aggregation function. |
scalar, Series or DataFrame, depending on the object and aggregation specification.
import pandas as pd
df = pd.DataFrame({"A": [1, 4, 7], "B": [2, 5, 8]})
result = df.agg({"A": ["sum", "min"], "B": "mean"})
print(result)Computes multiple aggregations for column A and the mean for column B.
You need totals, extrema, or averages for every column in one operation.
Different columns require different reductions, such as sum for one and mean for another.
You need several statistics for each column, such as sum and minimum.
You want a row-level statistic across columns.
By default, agg uses axis=0, so each function is applied to every column. Set axis=1 or axis="columns" to aggregate across each row instead.
Follow-up: What result shape should you expect from several functions? A DataFrame is returned, with aggregation names represented in the result index when aggregating columns.
func can be a callable, a string naming an operation, a list of operations, or a dictionary mapping columns to operations. A list requests multiple aggregations, while a dictionary allows different operations for different columns.
Follow-up: How would you combine named results? Use named aggregation keyword arguments such as x=("A", "max") and y=("B", "min").
For DataFrame.agg, a single aggregation generally produces a Series, while multiple aggregations produce a DataFrame. The documented return possibilities are scalar, Series, or DataFrame depending on the object and aggregation used.
Follow-up: What is the related method name? aggregate is an alias for agg, so either spelling invokes the same operation.
DataFrame.aggregateDataFrame.applySeries.aggSeries.aggregate