pandas/text-time-key
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| pandas | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
Grouping on dates formatted as text turns every date into text first. Group on dt.to_period("M"), dt.floor("h") or pd.Grouper instead.
monthly = df.groupby(df["time"].dt.strftime("%Y-%m"))["load"].sum()monthly = df.groupby(df["time"].dt.to_period("M"))["load"].sum()What the rule reports
Section titled “What the rule reports”The rule reports df.groupby(df["d"].dt.strftime("%Y-%m")), which turns every date into text to build the group key.
How to fix it
Section titled “How to fix it”xpd check --fix --unsafe-fixes rewrites common dt.strftime(...) groupby keys ("%Y", "%Y-%m" to dt.to_period(...), and "%Y-%m-%d", "%Y-%m-%d %H", "%Y-%m-%d %H:%M" to dt.floor(...)). Other formats remain manual.
The result has a PeriodIndex instead of text labels. On a column with a time zone, to_period drops the zone and gives a UserWarning, so group on pd.Grouper(key="time", freq="MS") instead.
Diagnostic message
Section titled “Diagnostic message”Grouping on formatted text is slow. Group on dt.to_period("M") or dt.floor("h") instead. On a column with a time zone to_period drops the zone and warns, so group on pd.Grouper(key=..., freq="MS") there.See all rules in the pandas pack.