How do you calculate group statistics like count and mean using Pandas groupby? | A1Lab@MZeeshanM to PythonEnglish • 4 days ago

How do you calculate group statistics like count and mean using Pandas groupby?

message-square
0

Chain .groupby("col") with .agg(...) using named aggregation tuples (new_col=("target_col", "func")) to compute multiple statistics like count and mean with clean, flat column names—or call .groupby("col")["target_col"].agg(["count", "mean"]) when summarizing a single column.

Basic Example

import pandas as pd

df = pd.DataFrame({
    "department": ["Sales", "Sales", "Engineering", "Engineering", "Engineering"],
    "employee": ["Alice", "Bob", "Charlie", "David", "Eve"],
    "salary": [70000, 80000, 110000, 120000, None],
    "bonus": [5000, 7000, 10000, 12000, 9000],
})

# 1. Recommended: Named aggregation produces clean, single-level column names
summary = df.groupby("department", as_index=False).agg(
    total_rows=("employee", "size"),       # Counts all rows (including NaN)
    valid_salaries=("salary", "count"),    # Counts non-null salary values only
    avg_salary=("salary", "mean"),
    total_bonus=("bonus", "sum"),
)
print(summary)
#     department  total_rows  valid_salaries  avg_salary  total_bonus
# 0  Engineering           3               2    115000.0        31000
# 1        Sales           2               2     75000.0        12000

# 2. Single-column shorthand: Aggregate one Series with a list of functions
salary_stats = df.groupby("department")["salary"].agg(["count", "mean", "median", "std"])

Key Details & Edge Cases

  • "count" vs. "size" for missing (NaN) values:
    • "count" excludes NaN / None values per column (so Engineering has valid_salaries = 2 because Eve’s salary is None).
    • "size" counts all rows in each group regardless of NaN values (total_rows = 3). Note that df.groupby("department").size() returns a single Series of row counts per group.
  • Missing groups when grouping on NaN keys (dropna=False):
    • By default (dropna=True), Pandas silently drops groups whose grouping key is NaN or None. Pass dropna=False (df.groupby("department", dropna=False).agg(...)) if you want missing-category rows preserved as their own group.
  • Keep group keys as regular columns instead of the row index (as_index=False):
    • By default (as_index=True), Pandas sets the grouping column(s) as the DataFrame index. Pass as_index=False (or chain .reset_index()) to keep group keys as ordinary columns ready for merging or CSV export.
  • Flattening MultiIndex columns when aggregating multiple columns without named tuples:
    • Running df.groupby("department")[["salary", "bonus"]].agg(["count", "mean"]) creates a 2-level MultiIndex header (("salary", "count"), ("salary", "mean"), …). Prefer named aggregation (avg_salary=("salary", "mean")) or flatten afterward with res.columns = ["_".join(col).strip("_") for col in res.columns].
  • Broadcasting group stats back to every original row (transform):
    • If you want to add a column to the original DataFrame (e.g., each employee’s department average) without collapsing rows, use .transform("mean") instead of .agg("mean"):
      df["dept_avg_salary"] = df.groupby("department")["salary"].transform("mean")
      
  • Avoid numeric_only errors on mixed-type DataFrames: Calling df.groupby("department").mean() directly on a DataFrame containing string columns ("employee") raises TypeError: agg function failed [how->mean,dtype->object] in Pandas 2.0+. Always select numeric target columns explicitly or pass numeric_only=True (df.groupby("department").mean(numeric_only=True)).

Comparison of Pandas groupby Aggregation Patterns

Pattern Syntax Output Shape & Headers Counts NaN Values? Best Used When
Named Aggregation (.agg) df.groupby("g").agg(n=("x", "count"), avg=("x", "mean")) DataFrame with flat, custom column names No ("count") / Yes ("size") Production pipelines needing multiple metrics across multiple columns cleanly.
Single-Column .agg([...]) df.groupby("g")["x"].agg(["count", "mean"]) DataFrame with count and mean columns No Quickly summarizing one target Series with several built-in or custom functions.
Group Row Counts (.size()) df.groupby("g").size().reset_index(name="n") 2-column DataFrame of group frequencies Yes (includes NaN cells) Counting total records per group regardless of missing values in individual columns.
Row-Level Broadcast (.transform) df.groupby("g")["x"].transform("mean") Series aligned to original DataFrame index No Computing group-relative features (e.g., x - group_mean or share of group total).