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

Multiple aggregations

Pass a list of functions to get several summary numbers per group at once.

In this page:

  1. Multiple aggregations
Syntax
python
df.groupby("column")["value_column"].agg(["sum", "mean", "count"])

Multiple aggregations

groupby(...)[col].agg(["sum", "mean", "count"]) returns a column per function. On several columns it produces hierarchical column names. You can also pass your own functions alongside built-in names.

Note: Flatten multi-level columns with df.columns = ["_".join(c) for c in df.columns].

Example: Multiple aggregations

python
import pandas as pd

df = pd.DataFrame({"dept": ["A", "B", "A", "B"], "salary": [100, 200, 150, 250]})
print(df.groupby("dept")["salary"].agg(["sum", "mean", "count"]))
print(df.groupby("dept")["salary"].agg(["min", lambda s: s.max() - s.min()]))

# Output:
#       sum   mean  count
# dept
# A     250  125.0      2
# B     450  225.0      2
#       min  <lambda_0>
# dept
# A     100          50
# B     200          50
Related Topics
Common Mistakes
  1. Confusing multi-level columns
  2. Passing functions that fail on text
  3. Forgetting the group key is the index
Chapter Summary
  • A list of functions gives multiple columns
  • Multiple value columns create hierarchical headers
  • Custom functions are allowed
  • Flatten headers when needed
🔒

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.