pandas/strftime-date-part
| Rule | strftime-date-part |
|---|---|
| Pack | pandas |
| Severity | warning |
| Fix | unsafe, with xpd check --fix --unsafe-fixes |
| Library versions | every version |
Formatting dates as text and parsing a number back out was 33 to 198 times slower than reading the part. Read it through .dt, as in df["d"].dt.year.
year = df["time"].dt.strftime("%Y").astype(int)weekday = df["time"].dt.strftime("%A")year = df["time"].dt.yearweekday = df["time"].dt.day_name()What the rule reports
Section titled “What the rule reports”The rule reports df["d"].dt.strftime("%Y").astype(int), the same with %m, %H and %j, and dt.strftime("%A") and "%B", which were 33 to 198 times slower than the date part on 1,000,000 rows.
How to fix it
Section titled “How to fix it”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["d"].dt.year, df["d"].dt.day_name().
The fixes are unsafe, because a date part is int32 where astype(int) gave int64, and day_name is English where strftime follows the locale.
Message
Section titled “Message”xpd prints this message with the issue. A name that starts with $ stands for code from your file.
This formats every date as text and parses the text back into a number. Read the part with $S.dt.year.Browse the other rules of the pandas pack.