Sub topic 6
Upsampling: creating a finer time grid
Upsampling means resampling to a finer frequency than your data has, for example weekly values onto a daily grid. This chapter assumes you can build a DatetimeIndex, read frequency strings such as "D" and "h", and downsample with resample().sum(). It covers how the new grid is built, what the new rows contain, and the errors that appear when the grid is created but not filled. Fill strategies (ffill, bfill, interpolate) get their own chapter, so they appear here only where needed.
What upsampling does
When you downsample, many rows fall into one bin and you must reduce them to one value. Upsampling is the opposite case: each bin holds zero or one original rows. Most of the new bins are empty, so there is nothing to aggregate. pandas creates the finer grid and leaves the new rows empty until you decide how to fill them.
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)
daily = s.resample("D").asfreq()
print(len(daily))
print(daily.head(3))The weekly series has 3 rows, and the daily result has 15. The first three lines of output show 10.0 on 2024-01-01 followed by NaN on 2024-01-02 and 2024-01-03. The original values keep their timestamps. Every other day is a new label with no data.
How the grid is built
resample("D") builds the grid from three pieces of information:
- The first and last timestamps in the index.
- The target frequency.
- The bin alignment rules (
origin,offset), which later chapters cover.
The first label is the first timestamp rounded down to the frequency. If your first timestamp is 2024-01-01 09:30 and you resample to "D", the first label is 2024-01-01 00:00. The grid runs at the target frequency until it covers the last timestamp.
Choosing what the new rows contain
The method you call on the Resampler decides the content of the new rows. All of these work on an upsampled series, but they behave differently.
| Method | Value in a new (empty) row | Typical use |
|---|---|---|
| `asfreq()` | `NaN` | Create the grid, then handle gaps yourself |
| `ffill()` | Last earlier original value | State that stays true until it changes (a price, a setting) |
| `bfill()` | Next later original value | Values that apply to the period before them |
| `nearest()` | Closest original value in time | Sensor readings with small timing jitter |
| `interpolate()` | Linear estimate between neighbours | Smoothly changing quantities |
| `sum()` | `0` | Rarely what you want when upsampling |
| `mean()` | `NaN` | Same result as `asfreq()` when each bin has one row |
The next example shows the sum() result, which surprises many people.
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.resample("D").sum().head(3))
print(s.resample("D").sum(min_count=1).head(3))
print(s.resample("D").mean().head(3))The first call gives 0.0 for 2024-01-02 and 2024-01-03, because the sum of an empty bin is 0. With min_count=1, a bin needs at least one value, so those rows are NaN. mean() also gives NaN. The zeros from the first call are not missing data in any sense pandas can detect later, so dropna() or isna() will not find them.
Filling the new rows
You can chain a fill method directly on the resampler. Forward fill repeats the last known value:
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)
filled = s.resample("D").ffill()
print(filled["2024-01-01":"2024-01-09"])Each day from 2024-01-01 to 2024-01-07 is 10.0, and 2024-01-08 and 2024-01-09 are 20.0. Calling s.resample("D").interpolate() instead gives 10.0, 11.428571, 12.857143, ... on the way to 20.0 on 2024-01-08.
Both ffill() and bfill() accept limit, the largest number of consecutive new rows to fill. Rows beyond the limit stay NaN:
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)
limited = s.resample("D").ffill(limit=2)
print(limited["2024-01-01":"2024-01-08"])The output is 10.0 on 01-01, 01-02 and 01-03, then NaN from 01-04 to 01-07, then 20.0 on 01-08. A limit is a cheap safeguard when a long gap should not be papered over with a stale value.
Timestamps that are not on the grid
The examples so far used timestamps that land exactly on the daily grid. Real data often does not.
import pandas as pd
idx = pd.to_datetime(
["2024-01-01 09:30", "2024-01-01 10:10", "2024-01-01 11:45"]
)
s = pd.Series([1.0, 2.0, 3.0], index=idx)
print(s.resample("h").asfreq())
print(s.resample("h").ffill())
print(s.resample("h").nearest())The hourly labels are 09:00, 10:00, 11:00. None of them equals an original timestamp. The behaviors differ:
asfreq()looks for exact matches only, so every row isNaN. The original values vanish from the result.ffill()takes the most recent value at or before each label.09:00isNaN, because nothing came before it.10:00is1.0and11:00is2.0.nearest()takes the closest value in time to each label.
If you want to keep every original observation and also have a regular grid, resampling is the wrong tool. Build the combined index yourself and reindex onto it (see the section on extending the grid).
The grid stops at the last timestamp
The upsampled grid ends at the last bin that holds an original timestamp. It does not extend to the end of the period that value describes. The weekly series above ends on 2024-01-15, so the daily result also ends on 2024-01-15, not 2024-01-21. If you need the grid to run further, reindex onto an explicit range:
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)
full_range = pd.date_range("2024-01-01", "2024-01-21", freq="D")
extended = s.reindex(full_range, method="ffill")
print(extended.tail(3))The last three rows are 30.0 on 2024-01-19, 2024-01-20 and 2024-01-21. The same reindex call also works when your target grid does not start where resample would start it.
Upsampling a DataFrame
On a DataFrame, the method applies to every column. If columns need different treatments, resample once to get the grid, then fill each column the way it needs:
import pandas as pd
idx = pd.date_range("2024-01-01", periods=3, freq="W-MON")
df = pd.DataFrame(
{"price": [10.0, 20.0, 30.0], "temperature": [3.0, 5.0, 4.0]},
index=idx,
)
grid = df.resample("D").asfreq()
grid["price"] = grid["price"].ffill()
grid["temperature"] = grid["temperature"].interpolate()
print(grid.head(3))Price stays at its last quoted value, and temperature is estimated between readings. This is more explicit than a single ffill() on the whole frame.
Common mistakes
- Treating totals as rates. Forward-filling a weekly total of 70 units onto seven daily rows makes each day show 70. Summing those days gives 490. For totals, divide by the number of new rows (here 7) after filling, or spread the value by a rule that fits your data.
- Using
sum()to create the grid. As shown above, it fills empty bins with0. - Expecting the original rows to survive. With off-grid timestamps,
asfreq()drops them. Only labels that match exactly keep their values. - Filling across large gaps. A forward fill over a month of missing data repeats one stale value. Use
limitor check for long gaps first. - Interpolating categories.
interpolate()makes sense for numeric measurements. For labels such as status codes, useffill().
Exercise
A series of monthly revenue totals (one row per month start) is resampled with s.resample("D").ffill(). A colleague then calls .sum() on the result to get yearly revenue. Why is the answer wrong, and what should be done instead?
Show answer
Forward fill copies each monthly total onto every day of that month, so the daily series contains the monthly figure about 30 times and the final sum is roughly 30 times too large. Either do not upsample (sum the original monthly rows directly), or divide each monthly total by the number of days in its month before summing, so the daily rows add back up to the original totals.
Exercise
For s = pd.Series([1.0, 2.0], index=pd.to_datetime(["2024-03-01", "2024-03-03"])), what do s.resample("D").asfreq() and s.resample("D").sum() return for 2024-03-02?
Show answer
asfreq() returns NaN for 2024-03-02, because the new label has no original value. sum() returns 0.0, because the sum of an empty bin is 0.