Skip to content

pandas/set-index-then-resample

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

Setting a column as the index only to resample takes an extra step. Pass the column to resample with on=.

daily = df.set_index("time").resample("D")["load"].sum()
daily = df.resample("D", on="time")["load"].sum()

The rule reports df.set_index("d").resample("D").sum(). The rule reports only a chain that ends in a named aggregation such as sum or mean, because asfreq raises with on=. A function passed to agg also sees other data with on=.

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.resample("D", on="d").sum(), which raises on an empty frame where the indexed form returned.

The result index can differ in name or dtype. With on=, the grouping column is also still available for selection after the resample.

resample takes on=, so the column does not have to become the index first. Write $X.resample($$$A, on=$COL).

See all rules in the pandas pack.