Skip to content

pandas/groupby-then-reset-index

Rule groupby-then-reset-index
Pack pandas
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

reset_index() after a groupby moves the keys back into columns in a second step. Pass as_index=False to groupby instead.

totals = df.groupby("region")["load"].sum().reset_index()
totals = df.groupby("region", as_index=False)["load"].sum()

The rule reports df.groupby("k")[["a", "b"]].sum().reset_index(). The fix is unsafe, because a key that is not a column comes back in another place.

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes df.groupby("k", as_index=False)[["a", "b"]].sum().

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

Pass as_index=False to groupby instead of resetting the index afterwards.

Browse the other rules of the pandas pack.