Sub topic 11
resample vs asfreq vs rolling
This chapter assumes you can build a DatetimeIndex, write frequency strings such as "W" and "MS", and call resample() with an aggregation. You have met resample() in the earlier chapters. Here you compare it with two methods that look similar: asfreq() and rolling().
Three tools, three questions
Each method answers a different question about a time series.
resample()asks: what is the summary of each calendar bin? It groups rows into bins and reduces each bin to one value.asfreq()asks: what is the value at each timestamp of a regular grid? It picks values and does not summarize anything.rolling()asks: what is the summary of the window that ends at each row? Windows overlap, and the result has one row per input row.
The usual mistake is to use asfreq() when you want an aggregate, or rolling() when you want a coarser frequency.
A side-by-side example
The series below has 14 daily values, 0 to 13, starting on Monday 2024-01-01.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=14, freq="D")
s = pd.Series(range(14), index=idx, dtype=float)
print(s.resample("W").mean())
print(s.asfreq("W"))
print(s.rolling(7).mean())The three calls return different shapes and different numbers:
resample("W").mean()returns 2 rows. The Sunday 2024-01-07 holds the mean of 0 to 6, which is 3.0. The Sunday 2024-01-14 holds the mean of 7 to 13, which is 10.0.asfreq("W")also returns 2 rows, labeled with the same two Sundays. It does not average. It returns the single value found at each Sunday, which is 6.0 and 13.0.rolling(7).mean()returns 14 rows. The first 6 areNaNbecause a full window of 7 rows does not exist yet. From 2024-01-07 on, each row holds the mean of the 7 rows ending there. The values on the two Sundays are 3.0 and 10.0.
The rolling values on those two Sundays equal the resample values by coincidence, because the rolling window happens to line up with the weekly bin on those days. The rolling result also contains values for every other day, such as 4.0 on Monday 2024-01-08. Those windows straddle two calendar weeks, and resample() never produces them.
| Property | `resample()` | `asfreq()` | `rolling()` |
|---|---|---|---|
| Output rows | One per bin | One per grid timestamp | One per input row |
| Combines several rows | Yes, with an aggregation | No | Yes, with an aggregation |
| Windows overlap | No | Not applicable | Yes |
| Changes the frequency | Yes | Yes | No |
| Needs an aggregation call | Yes | No | Yes |
How asfreq works
asfreq() builds a regular DatetimeIndex from the first to the last timestamp at the requested frequency. It then looks up each grid timestamp in your data. If a timestamp exists, you get its value. If it does not, you get NaN, or a filled value if you pass method.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=3, freq="W-MON")
s = pd.Series([10.0, 20.0, 30.0], index=idx)
print(s.asfreq("D"))
print(s.asfreq("D", method="ffill"))
print(s.resample("D").ffill())The first call returns 15 daily rows. Only the three Mondays have values, and every other row is NaN. The second call fills each gap with the last known value. The third call gives the same result as the second. For upsampling, asfreq(freq, method="ffill") and resample(freq).ffill() are interchangeable. Use whichever reads better in your code.
asfreq() has one further parameter. fill_value replaces only the gaps that asfreq() itself created. It does not replace NaN that was already in the data.
The silent NaN gotcha
When you downsample with asfreq(), a grid timestamp that does not exist in your data produces NaN. Suppose your series has business days only and you call asfreq("W"). The grid is Sundays, your data has no Sundays, and every value is NaN.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="B")
s = pd.Series(range(10), index=idx, dtype=float)
print(s.asfreq("W").isna().all())
print(s.resample("W").last())The first line prints True. The second returns one value per week, because resample() takes whatever rows fall inside each bin. Use resample(...).last() when you want the final observation of each period. Use asfreq() only when you know the target timestamps exist.
How rolling works with time
rolling() accepts an integer or a time offset as its window. The two behave differently when the data has gaps.
- An integer window such as
rolling(3)counts rows. If rows are missing, the window covers a longer span of time. - An offset window such as
rolling("3D")covers a fixed span of time. By default the window is closed on the right, so it includes the current timestamp and excludes the one exactly 3 days earlier. The index must be sorted. - With an integer window,
min_periodsdefaults to the window size. With an offset window it defaults to 1, so you get no leadingNaN.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-05", "2024-01-06"])
s = pd.Series([1, 2, 3, 4], index=idx)
print(s.rolling("3D").sum())
print(s.resample("D").sum())The rolling result has 4 rows with values 1, 3, 3 and 7. On 2024-01-05 the window covers January 3 to 5, so January 2 drops out. On 2024-01-06 the window holds 3 and 4. The resample result has 6 rows with values 1, 2, 0, 0, 3 and 4. It creates the missing days and fills the empty bins with 0, as the empty-bin chapter described.
Combining resample and rolling
The two tools often work together. A common pattern is to put irregular data on a regular grid first, then smooth it:
smooth = s.resample("D").sum().rolling(7, min_periods=1).mean()Once resample("D") has produced exactly one row per day, an integer window of 7 means 7 days. Without that first step, the same integer window would mean 7 rows, whatever span of time those rows cover.
You can also go the other way. To get a monthly series of 30-day rolling means, compute rolling("30D").mean() first. Then take .resample("MS").last() to keep the value at the end of each month. Order matters: the rolling window sees every row, and the resample then selects from the result.
Choosing between them
The rest of this section gives practical rules for each case.
- Use
resample()when the period is a calendar unit, such as a week or month. It handles uneven month lengths and empty bins for you. - Use
asfreq()when you only need a regular grid. Typical cases are inserting explicitNaNrows for missing timestamps, or taking a snapshot of a series that is already sampled at the grid points. - Use
rolling()when you want a trend line or moving statistic that stays aligned with the original rows. - Use
resample(...).last()instead ofasfreq()when the snapshot timestamp might not exist in the data.
A last point is about labels. resample() labels each bin with its start or end, according to closed and label. asfreq() uses grid timestamps exactly. rolling() keeps the original labels, and each value describes the window that ends at that label. Take care when you join the outputs of the three methods. For example, a rolling value dated Sunday describes the 7 days ending Sunday, while a "W" resample value with the same date describes the same days only because "W" bins close on Sunday.
Exercise
A daily series has values for every day of 2024. You call s.asfreq("MS") and s.resample("MS").first(). The January 1 value is 5 and the January 2 value is 9. What does each call return for January, and when would the two results differ?
Show answer
Both return 5 for January, because the first row of each month is the value at the month-start timestamp. They differ when the month-start timestamp is missing from the data. If the series has no row for January 1 (for example, it starts on January 2), asfreq("MS") returns NaN for January, while resample("MS").first() returns 9, the first row inside the January bin.