Skip to content

pandas/rename-after-agg

Pack Severity Fix Versions
pandas warning unsafe, with xpd check --fix --unsafe-fixes All versions

Renaming columns right after agg names them in a second step. Name them in agg itself, as in agg(b_mean=("b", "mean")).

summary = df.groupby("region").agg({"load": "mean"}).rename(columns={"load": "mean_load"})
summary = df.groupby("region").agg(mean_load=("load", "mean"))

The rule reports g.agg({"b": "mean"}).rename(columns={"b": "b_mean"}).

xpd check --fix --unsafe-fixes rewrites one- and two-column literal .agg({...}).rename(columns={...}) calls with valid identifier names to named aggregations (agg(b_mean=("b", "mean"))). Larger or dynamic mappings remain manual.

Name the result columns in agg itself, as in agg(b_mean=("b", "mean")), instead of renaming them afterwards.

See all rules in the pandas pack.