Skip to content

pandas/text-time-key

Rule text-time-key
Pack pandas
Severity warning
Fix none, edit by hand
Library versions every version

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()

The rule reports df.groupby(df["d"].dt.strftime("%Y-%m")), which turns every date into text to build the group key.

xpd has no automatic fix, so make the change by hand.

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.

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

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.

Browse the other rules of the pandas pack.