The .agg() Method in Pandas – Powerful Aggregations in Python 2026

Data Manipulation Mar 18, 2026

The .agg() Method in Pandas – Powerful Aggregations in Python 2026

The .agg() (aggregate) method is one of the most flexible and powerful tools in Pandas for performing custom summary statistics. In 2026, using .agg() with method chaining has become the standard way to create clean, readable, and efficient aggregation pipelines.

TL;DR — Why .agg() is Essential

  • Apply multiple aggregation functions at once
  • Use different functions for different columns
  • Works beautifully with groupby()
  • Supports custom functions and named outputs

1. Basic Usage of .agg()

import pandas as pd

# Create a small demo file so this example runs as-is
# (in your project, sales_data.csv is your real export)
import numpy as np
rng = np.random.default_rng(42)
n = 60
pd.DataFrame({
    "order_date": pd.date_range("2025-10-01", periods=n, freq="3D"),
    "customer_id": rng.integers(101, 121, n),
    "customer_name": rng.choice([" ana", "ben ", "chen", "dana"], n),
    "product_id": rng.integers(1, 9, n),
    "region": rng.choice(["North", "South", "East", "West"], n),
    "category": rng.choice(["Electronics", "Books", "Home"], n),
    "payment_method": rng.choice(["card", "cash", "wallet"], n),
    "segment": rng.choice(["consumer", "business"], n),
    "quantity": rng.integers(1, 6, n),
    "amount": rng.uniform(50, 2500, n).round(2),
}).assign(
    ship_date=lambda d: d["order_date"] + pd.Timedelta(days=2),
    status=lambda d: np.where(d["amount"] > 2000, "priority", "standard"),
).to_csv("sales_data.csv", index=False)

df = pd.read_csv("sales_data.csv", parse_dates=["order_date"])

summary = df.agg({
    "amount": ["count", "sum", "mean", "median", "min", "max", "std"],
    "quantity": ["sum", "mean"],
    "customer_id": "nunique"
}).round(2)

print(summary)

2. Combined with groupby() – Most Common Pattern

result = (
    df
    .groupby(["region", df["order_date"].dt.to_period("M")])
    .agg({
        "amount": ["sum", "mean", "count"],
        "quantity": "sum",
        "customer_id": "nunique"
    })
    .round(2)
)

# Rename columns for cleaner output
result.columns = ["total_sales", "avg_sale", "order_count", "total_quantity", "unique_customers"]
print(result)

3. Advanced .agg() with Named Outputs and Custom Functions

def range_func(x):
    return x.max() - x.min()

summary = (
    df
    .groupby("region")
    .agg(
        total_sales=("amount", "sum"),
        avg_sale=("amount", "mean"),
        sales_range=("amount", range_func),
        unique_customers=("customer_id", "nunique")
    )
    .round(2)
)

4. Best Practices in 2026

  • Use dictionary syntax with column → list of functions for clarity
  • Use named aggregation syntax (new_name=("column", "func")) for clean column names
  • Combine .agg() with groupby() and method chaining
  • Define small custom functions when built-in ones are not enough
  • Always round final results for readability

What .agg() Actually Does

.agg() (an alias of .aggregate()) applies one or more reducing functions and returns their results in a single object. A reducing function turns many values into one: a sum, a mean, a count or the largest value. You can pass a string such as "sum", a list of strings, a dictionary that maps columns to functions, or your own function. String names are preferred because pandas runs its fast built-in versions.

On a whole DataFrame the result is a Series or a small table; after groupby() you get one row per group, which is the pattern most reports use.

Worked Example: A Compact Store Report

Here one call produces several statistics per store with readable column names.

import pandas as pd

sales = pd.DataFrame({
    "store": ["A", "A", "B", "B", "B"],
    "amount": [100.0, 150.0, 80.0, 120.0, 40.0],
    "qty": [2, 3, 1, 4, 1],
})

report = sales.groupby("store").agg(
    orders=("amount", "size"),
    revenue=("amount", "sum"),
    avg_order=("amount", "mean"),
    units=("qty", "sum"),
)
print(report.round(1))
#        orders  revenue  avg_order  units
# store
# A           2    250.0      125.0      5
# B           3    240.0       80.0      6

Named aggregation keeps the output flat, so the result can go straight into a chart or a CSV without renaming MultiIndex columns.

Common Mistakes

  • Passing a function that does not reduce: functions that return a Series of the same length belong in transform()
  • Using lambdas everywhere: they are slower and produce unclear column names like <lambda_0>
  • Confusing "size" and "count": size counts rows, count skips missing values
  • Expecting .agg() to change the original: it always returns a new object

Quick Summary

  • .agg() runs one or many reducing functions in one call
  • Use named aggregation for clean column names
  • Prefer string function names for speed and clarity

Conclusion

The .agg() method is the modern, Pythonic way to perform powerful aggregations in Pandas. In 2026, mastering .agg() together with groupby() and method chaining allows you to write concise, readable, and highly efficient data summarization code that scales from small datasets to millions of rows.

Next steps:

  • Replace your multiple separate .sum(), .mean() calls with a single, well-structured .agg() operation

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices