← Back to Pandas Course | Chapter 7: Grouping & Aggregation | Lesson 2 of 7

agg() functions

agg applies one or several summary functions to your groups in a single call.

In this page:

  1. agg() functions
Syntax
python
df.groupby("column").agg("function_name")
df.groupby("column").agg({"column1": "sum", "column2": "mean"})

agg() functions

agg accepts a function name, a list of names, or a dict mapping columns to functions. Common choices are sum, mean, min, max, count and std. It works on Series, DataFrames and groupby objects.

Note: A dict such as {"salary": "mean", "age": "max"} applies different functions per column.

Example: agg() functions

python
import pandas as pd

df = pd.DataFrame({"dept": ["A", "B", "A", "B"], "salary": [100, 200, 150, 250], "age": [30, 40, 35, 45]})
print(df.groupby("dept").agg({"salary": "mean", "age": "max"}))
print(df["salary"].agg(["min", "max"]))

# Output:
#       salary  age
# dept
# A      125.0   35
# B      225.0   45
# min    100
# max    250
# Name: salary, dtype: int64
Related Topics
Common Mistakes
  1. Using the wrong function name string
  2. Forgetting agg returns a new object
  3. Applying numeric functions to text columns
Chapter Summary
  • agg takes names, lists or dicts
  • Works with groupby
  • Dicts vary functions per column
  • Common: sum, mean, min, max
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.