Sub topic 2
Frequency strings: describing the target frequency
Every resample() call starts with a frequency, such as "W", "MS" or "15min". That string tells pandas how wide each bin is and where the bins start. This chapter covers how those strings are built, which ones you will use most, and which ones cause mistakes.
You should already be comfortable with a Series or DataFrame that has a DatetimeIndex, as in the previous chapter. The examples assume pandas 2.2 or later. Some alias names changed in that release, and the changes are covered below.
What a frequency string is
A frequency string is shorthand for an offset object. An offset is a rule for stepping from one timestamp to the next, such as "one day", "the end of the month" or "every 15 minutes". When you pass a string to resample(), date_range() or asfreq(), pandas converts it with to_offset(). You can call that function yourself to see what a string means:
from pandas.tseries.frequencies import to_offset
for alias in ["D", "B", "W", "W-MON", "MS", "ME", "QS", "YE", "15min", "1h30min"]:
print(f"{alias:>8} -> {to_offset(alias).freqstr}")The output shows how pandas normalizes each string:
D -> D
B -> B
W -> W-SUN
W-MON -> W-MON
MS -> MS
ME -> ME
QS -> QS-JAN
YE -> YE-DEC
15min -> 15min
1h30min -> 90minTwo things stand out. Plain "W" expands to "W-SUN", so weeks end on Sunday by default. Plain "QS" and "YE" get a default anchor month. The string "1h30min" collapses to "90min", because both describe the same fixed span of time.
The anatomy of a string
A frequency string has up to three parts:
- An optional integer multiple, such as
2in"2D"or15in"15min". - A base alias, such as
D,W,MSormin. - An optional anchor after a hyphen, such as
-MONin"W-MON"or-OCTin"QS-OCT".
The multiple makes the bin wider. "2W" means two-week bins. The anchor shifts where the bins fall. Weekly anchors are weekday names (MON to SUN). Quarterly and yearly anchors are month names (JAN to DEC).
The aliases you will use most
| Alias | Meaning | Bin boundary |
|---|---|---|
| `D` | Calendar day | Midnight |
| `B` | Business day (Monday to Friday) | Midnight, weekends skipped |
| `W` or `W-SUN` | Weekly, ending Sunday | Sunday |
| `W-MON` ... `W-SAT` | Weekly, ending on the named day | That weekday |
| `MS` | Month start | First of the month |
| `ME` | Month end | Last day of the month |
| `QS` | Quarter start | First day of Jan, Apr, Jul, Oct |
| `QE` | Quarter end | Last day of Mar, Jun, Sep, Dec |
| `YS` | Year start | January 1 |
| `YE` | Year end | December 31 |
| `h` | Hour | Top of the hour |
| `min` | Minute | Start of the minute |
| `s` | Second | Start of the second |
| `ms`, `us`, `ns` | Milli-, micro-, nanosecond | Start of the unit |
The start and end variants matter. "MS" and "ME" produce the same number of bins, but the timestamps that label them differ. "MS" labels a bin 2024-01-01. "ME" labels the same month 2024-01-31. The labeling rules are covered in the chapter on bin edges.
Renamed aliases
Pandas 2.2 renamed several aliases. The old forms emit a FutureWarning, and newer releases reject them:
| Old | New |
|---|---|
| `M` | `ME` |
| `Q` | `QE` |
| `A`, `Y` | `YE` |
| `H` | `h` |
| `T` | `min` |
| `S` | `s` |
| `L`, `U`, `N` | `ms`, `us`, `ns` |
The reason for the change is ambiguity. A bare "M" could be read as month start or month end. A bare "T" is not obviously minutes. Most old tutorials still use the old names, so expect to translate them.
Multiples and compound strings
A leading integer repeats the base unit:
import pandas as pd
idx = pd.date_range("2024-01-01 00:00", periods=60, freq="min")
s = pd.Series(range(60), index=idx)
print(s.resample("15min").sum())The 60 one-minute values fall into four 15-minute bins. The sums are 105 (values 0 to 14), 330, 555 and 780. They add up to 1770, which is the sum of 0 to 59.
You can chain fixed-length units into one string, such as "1h30min". Pandas adds them into a single 90-minute step. Chaining only works for fixed-length units (hours, minutes, seconds and smaller). A string like "1MS2D" is not valid, because a month has no fixed length to add days to.
Fixed-length and calendar-based offsets
Offsets fall into two groups, and the difference explains most surprising behavior.
- Fixed-length offsets (
h,min,s, and smaller) always span the same amount of time. Pandas calls these tick offsets. - Calendar offsets (
W,MS,ME,QS,YE,B) depend on the calendar. A month can have 28, 29, 30 or 31 days.
"D" is a calendar day. On a time-zone-aware index, a day that crosses a daylight saving change can be 23 or 25 hours long. Use "24h" if you want exactly 24 hours. The time-zone chapter covers this.
Anchors change which bins you get
The anchor decides where a bin ends. This example uses 14 days that start on a Monday. It resamples the same data with the default "W" and with "W-MON":
import pandas as pd
idx = pd.date_range("2024-01-01", periods=14, freq="D")
s = pd.Series(range(14), index=idx)
print(s.resample("W").sum())
print(s.resample("W-MON").sum())With "W", bins end on Sunday. The labels are 2024-01-07 (value 21) and 2024-01-14 (value 70).
With "W-MON", bins end on Monday, so January 1 sits alone in the first bin. You get three bins: 2024-01-01 (value 0), 2024-01-08 (value 28) and 2024-01-15 (value 63). Both results add up to 91, so no rows are lost or counted twice. The data is simply grouped differently.
Use an anchor when your reporting week does not end on Sunday. For example, a retail week that closes on Saturday uses "W-SAT". Fiscal quarters work the same way. "QS-FEB" starts quarters in February, May, August and November. "YE-MAR" ends each year on March 31.
Offset objects instead of strings
Strings are convenient, but you can also pass an offset object from pd.offsets. This is useful when you build the rule in code:
import pandas as pd
idx = pd.date_range("2024-01-01", periods=14, freq="D")
s = pd.Series(range(14), index=idx)
rule = pd.offsets.Week(weekday=0) # weeks anchored on Monday
print(rule.freqstr) # W-MON
print(s.resample(rule).sum())This gives the same result as "W-MON". The object form avoids typos in alias names, and your editor can complete it.
Reading a frequency from existing data
If you are unsure which frequency your data has, ask pandas:
import pandas as pd
idx = pd.date_range("2024-01-01", periods=5, freq="D")
print(pd.infer_freq(idx)) # D
print(idx.freq) # <Day>infer_freq() returns None when the index is irregular or has gaps. idx.freq is only set if the index was created with a frequency (for example by date_range). An index loaded from a file usually has freq=None, even if the spacing is regular. That does not stop resample() from working. resample() bins by timestamp value and does not need freq to be set.
Common errors
ValueError: Invalid frequency: ...means the string is not a known alias. Check the case and look for renamed aliases.FutureWarningabout'M'or'H'means you are using a deprecated alias. Switch toMEorh.- Wrong bin labels usually mean you picked start (
MS) when you wanted end (ME), or the reverse. - Weekly totals that do not match a calendar week usually mean the default Sunday anchor does not match your week.
Exercise
Your company's fiscal year ends on June 30. You have daily revenue data and want one total per fiscal year, labeled by the last day of that year. Which frequency string do you pass to resample(), and which would you use for fiscal quarters that begin in July?
Show answer
Use "YE-JUN" for fiscal years, so each bin ends on June 30 and is labeled with that date. For quarters that begin in July, use "QS-JUL". This gives quarters starting in July, October, January and April, labeled by their first day.
Exercise
What does s.resample("2W-FRI") do, and how does it differ from s.resample("W-FRI")?
Show answer
Both use bins that end on Friday. "W-FRI" makes each bin one week wide. "2W-FRI" makes each bin two weeks wide, which doubles the span covered by each total and halves the number of bins.