skip to content

In pandas, how do `asfreq` and `resample` differ when you change a series' frequency, and how do you fill the gaps after upsampling?

level: middleimportance: should knowfreq 42%

answer

  1. reindex versus group
  2. picks a value, does not combine
  3. upsampling creates empty rows
  4. fill on the Resampler, with a limit

basics

~20 s

asfreq reindexes to the new frequency and keeps only values stamped exactly on the new timestamps; resample groups rows into buckets and aggregates them. After upsampling, new rows are NaN until you ffill, bfill or interpolate them.

solid answer

~30 s

`asfreq('D')` is a reindex onto `date_range(first, last, freq='D')`: each output row takes the value stamped exactly at that timestamp, so on hourly visits it returns the midnight hour, not the day's total. `resample('D').sum()` groups every row of the day and aggregates. Upsampling, daily to hourly, creates rows that had no data: `s.resample('h').asfreq()` leaves them `NaN`, `.ffill()` or `.bfill()` carries values with an optional `limit=`, and `.interpolate()` draws a line between them. Beware `s.resample('h').sum()` when upsampling: the new buckets are empty and sum to 0, not to the day's value.

code

python · 15 lines
python
import pandas as pd

hourly = pd.Series(
    range(48),
    index=pd.date_range("2026-03-02", periods=48, freq="h"),
    name="visits",
)
print(hourly.asfreq("D"))          # 2 rows: 0 and 24, the midnight values
print(hourly.resample("D").sum())  # 2 rows: 276 and 852, the day totals

target = pd.Series(
    [500.0, 650.0], index=pd.to_datetime(["2026-03-02", "2026-03-03"])
)
up = target.resample("6h").asfreq()  # 5 rows; 06:00, 12:00, 18:00 are NaN
print(up.ffill())                    # 500.0 carried to the three new rows

go deeper

for a junior

Recall that asfreq picks values at the new timestamps while resample groups and aggregates, and that upsampled rows start out empty.

for a middle

Explain asfreq as a reindex, the Resampler fill methods with limit, and why sum on an upsample produces zeros rather than repeated values.

for a senior

Choose the fill from what the column means, a level, a total or a measurement, and check the range end and limit so filled values never hide a long outage.

for a principal

Make upsampling rules explicit in shared pipelines, since a silent ffill or zero fill changes what downstream metrics report without any error.

## Two operations that look alike Both `asfreq` and `resample` return data at a new frequency, which is why they get confused. Underneath they are different operations: - **`asfreq(freq)`** is a **reindex**. pandas builds the new index as `date_range(start, end, freq=freq)`, where `start` and `end` are the first and last timestamps of the original index, and looks up each new timestamp in the old data. A timestamp that existed keeps its value; one that did not becomes `NaN`, unless you pass `method='ffill'` / `'bfill'` or `fill_value=`. - **`resample(rule)`** is a **groupby on time**. Every original row falls into one bucket, and an aggregation combines each bucket's rows. | | `asfreq('D')` | `resample('D').sum()` | |---|---|---| | operation | reindex | group and aggregate | | rows between new timestamps | ignored | included in a bucket | | value at each new stamp | the single row stamped there | the bucket's aggregate | | new stamp with no matching row | `NaN` (or the fill) | `0` for sum, `NaN` for mean | ## Downsampling: why `asfreq` gives the wrong totals With hourly web traffic, `hourly.asfreq('D')` returns one row per day holding only the **00:00** hour. The other 23 hours are discarded, not summed. That is right when you want a snapshot ("the counter's value at midnight") and wrong for any total or average. For totals, use `hourly.resample('D').sum()`; for a snapshot, `resample('D').first()` or `.last()` makes the choice explicit and survives a missing midnight row. ## Upsampling: the new rows start empty Upsampling goes from a coarse frequency to a finer one, for example spreading a daily traffic target over hours so it can be compared with hourly actuals. The fine rows did not exist, so pandas has to be told what to put in them. On a `Resampler`, the upsampling methods are: 1. **`.asfreq()`**: reindex only, new rows are `NaN`. `Resampler.asfreq(fill_value=0)` puts a constant there instead. 2. **`.ffill(limit=None)`**: carry the last known value forward. With `limit=3` at most three new rows in a row are filled. 3. **`.bfill(limit=None)`**: carry the next known value backward. 4. **`.nearest(limit=None)`**: take whichever original value is closer in time. 5. **`.interpolate()`**: fill linearly (or by another method) between known points. `fill_value` and the fill methods act only on rows that the upsampling **created**; a `NaN` that was already present in the source stays `NaN`, as the `asfreq` docstring notes. Clean source gaps separately with the missing-data tools. ## The `sum()` trap when upsampling `daily.resample('6h').sum()` looks like it should spread or repeat the daily value, but each new 6-hour bucket is **empty**, and `Resampler.sum` defaults to `min_count=0`, so they become `0`. The day's value sits only in the 00:00 bucket. A chart of that series shows a spike every midnight and zeros between. Choose the fill that matches the meaning: - a **level** (a target, a price, a configuration) is carried with `ffill`; - a **total** that should be spread needs an explicit division, for example `daily.resample('6h').ffill() / 4`, and a decision about the last day; - a **smooth measurement** may be interpolated. ## The range ends at the last timestamp Both forms build the new index from the first to the last **original timestamp**. A daily series ending on 3 March upsampled to hours stops at `2026-03-03 00:00`, not at 23:00. If the last day needs all its hours, extend the index first, for example with `reindex(pd.date_range(start, end_of_day, freq='h'))`, then fill. ## Reading the worked example The snippet below makes the difference concrete with 48 hourly values numbered 0 to 47: 1. `hourly.asfreq('D')` returns two rows, `0` and `24`: the values stamped at the two midnights. The other 46 rows are not used. 2. `hourly.resample('D').sum()` returns `276` and `852`: the totals of hours 0 to 23 and 24 to 47. 3. `target.resample('6h').asfreq()` turns two daily targets into five 6-hourly rows, three of them `NaN`, and it stops at the second day's midnight. 4. `.ffill()` copies `500.0` into the three new rows; the last row keeps `650.0`. ## Choosing between them - Report at a coarser frequency: `resample(...).agg(...)`. - Snapshot at regular instants from a regular source: `asfreq(...)`. - Put a regular grid under irregular data and fill it: `resample(...).ffill()` or `.interpolate()`. - Fill only short gaps and leave long ones visible: pass `limit=`.

  • When upsampling, what is the difference between `s.resample('h').ffill()` and `s.resample('h').asfreq().ffill()`?
    The first fills only the rows the upsampling created, so a `NaN` already present in `s` stays `NaN`. The second reindexes first and then runs `Series.ffill` over everything, so it also fills those original `NaN`s from the value before them. Choose the first when source gaps should stay visible.
  • How do you upsample with `DataFrame.asfreq` and fill in one call?
    `df.asfreq('h', method='ffill')` reindexes to hourly and carries values forward; `fill_value=0` puts a constant in new rows instead. Both act only on rows created by the reindex. `asfreq` has no `limit`, so use `df.resample('h').ffill(limit=3)` when only short gaps should be filled.

  • asfreq('D') sums the hours of each day
  • resample('6h').sum() on daily data repeats the daily value
  • ffill after resampling also fills NaN already in the source
  • Upsampling extends to the end of the last day