Sub topic 7
Missing timestamps: regularize with asfreq() before shifting
This chapter assumes you know basic Python, how to create and index pandas Series and DataFrames, and how DatetimeIndex and pd.date_range work. It also assumes you have seen shift(periods) as a positional lag. If you haven't, read the earlier chapters on shift() first.
The problem: shift() counts rows, not days
shift(1) moves values by one row. It never looks at the timestamps. When every day has a row, "one row back" and "one day back" are the same thing. When a day is missing, they are not.
Start with the daily series used throughout this tutorial and remove one day:
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
irregular = s.drop(pd.Timestamp("2024-01-03"))
print(irregular)
print(irregular.shift(1))2024-01-01 10
2024-01-02 12
2024-01-04 11
Name: sales, dtype: int64
2024-01-01 NaN
2024-01-02 10.0
2024-01-04 12.0
Name: sales, dtype: float64Look at 2024-01-04. Its lag shows 12, which was recorded on 2024-01-02, two days earlier. If you meant "yesterday's sales", this value is wrong. Nothing warns you, because pandas did exactly what you asked: it moved values by one position.
This error is silent and shows up in many real datasets:
- Stores that close on some days.
- Sensors that drop readings.
- Stock prices, which have no rows for weekends and holidays.
- Event logs that only contain rows when something happened.
Detecting gaps
Before you lag a series, check whether its index is regular. Two quick checks work well.
print(pd.infer_freq(s.index))
print(pd.infer_freq(irregular.index))
steps = irregular.index.to_series().diff()
print(steps[steps > pd.Timedelta("1D")])D
None
2024-01-04 2 days
dtype: timedelta64[ns]pd.infer_freq() returns a frequency string such as "D" when the index follows a regular pattern, and None when it does not. It needs at least three timestamps. The second check takes the difference between consecutive timestamps and keeps the steps larger than one day. It tells you where the gaps are, and the first check only tells you that one exists.
A None result is not always a problem. A series that is meant to be irregular, such as trade timestamps, will return None. The check is useful when you expect a regular grid.
Regularizing with asfreq()
Series.asfreq(freq) returns a series on a complete, regular grid. It runs from the first timestamp to the last at the given frequency. Timestamps that were missing are inserted with NaN.
regular = irregular.asfreq("D")
print(regular)
print(regular.shift(1))2024-01-01 10.0
2024-01-02 12.0
2024-01-03 NaN
2024-01-04 11.0
Freq: D, Name: sales, dtype: float64
2024-01-01 NaN
2024-01-02 10.0
2024-01-03 12.0
2024-01-04 NaN
Freq: D, Name: sales, dtype: float64Now shift(1) means one calendar day back. On 2024-01-04 the lag is NaN, because 2024-01-03 has no recorded value. That NaN is correct: the data for the previous day is unknown, and the result says so. The earlier output, 12, was a plausible but false number.
Three side effects are worth noting:
- The index now carries
freq="D", which later operations such asshift(freq=...)androlling()can use. - The dtype changed from integer to float, because integers cannot hold
NaN. - The new row at 2024-01-03 exists in every later calculation. A moving average or a count now sees a row that has no data.
Deciding what to do with the new gaps
asfreq() exposes the gaps. It does not decide what they mean. Pick the treatment that matches what a missing row means in your data.
| Situation | Meaning of a missing row | Reasonable treatment |
|---|---|---|
| Daily sales for a store that was closed | No sales happened | `fill_value=0` |
| A sensor that reports only when its value changes | The value stayed the same | `method="ffill"` |
| A dropped network reading | The value is unknown | Leave `NaN` |
| A stock price on a weekend | Market was closed | Use a business-day frequency such as `"B"` instead of filling |
asfreq() has two parameters for this:
zero_filled = irregular.asfreq("D", fill_value=0)
print(zero_filled)
carried = irregular.asfreq("D", method="ffill")
print(carried)2024-01-01 10
2024-01-02 12
2024-01-03 0
2024-01-04 11
Freq: D, Name: sales, dtype: int64
2024-01-01 10
2024-01-02 12
2024-01-03 12
2024-01-04 11
Freq: D, Name: sales, dtype: int64fill_value applies only to timestamps that asfreq() inserted. A NaN that was already in your data stays NaN. method="ffill" has the same limit, so neither parameter repairs missing values you already had. Use fillna() or ffill() afterwards for those.
Filling before shifting has a cost. If you forward-fill a missing day and then lag it, the lag contains a value that was never observed on that day. For a forecasting model this can overstate how much information you have. Fill only when the fill reflects how the data is really generated.
Business days and other frequencies
The frequency you pass to asfreq() defines what "one step" means. For daily calendar data it is "D". For data that only exists on weekdays, use "B" (business day). With "B", a Friday-to-Monday step is a single row, so shift(1) on Monday gives Friday's value, which is usually what you want for market data.
prices = pd.Series(
[101.0, 102.5, 103.0, 101.5],
index=pd.to_datetime(["2024-01-04", "2024-01-05", "2024-01-08", "2024-01-09"]),
name="close",
)
print(prices.asfreq("B").shift(1))2024-01-04 NaN
2024-01-05 101.0
2024-01-08 102.5
2024-01-09 103.0
Freq: B, Name: close, dtype: float64Here 2024-01-06 and 2024-01-07 fall on a weekend, so "B" has no slot for them. Using "D" would have inserted two NaN rows and pushed Friday's value out of Monday's lag.
Alternatives to asfreq()
asfreq() is the simplest tool, but it has two limits: it covers only the range between the first and last timestamps, and it requires a clean index. Other options handle those cases.
reindex() for an explicit range
reindex() with a pd.date_range lets you choose the grid yourself. This is useful when several series must share the same range, or when you want to extend a series past its last observation:
full_range = pd.date_range("2024-01-01", "2024-01-05", freq="D")
print(irregular.reindex(full_range).shift(1))2024-01-01 NaN
2024-01-02 10.0
2024-01-03 12.0
2024-01-04 NaN
2024-01-05 11.0
Freq: D, Name: sales, dtype: float64shift(freq=...) to keep the original rows
Sometimes you want to keep the irregular rows and attach a calendar-based lag to each one. Shifting the index labels by one day does that, because assignment aligns on the index:
df = irregular.to_frame("sales")
df["lag1_calendar"] = irregular.shift(1, freq="D")
print(df) sales lag1_calendar
2024-01-01 10 NaN
2024-01-02 12 10.0
2024-01-04 11 NaNThe shifted series has labels 01-02, 01-03 and 01-05. Only 01-02 matches a row in df, so only that row gets a lag. The row for 2024-01-04 gets NaN because there is no observation for 2024-01-03. This gives the same answers as the asfreq() approach, without adding rows.
resample() when timestamps are off the grid
asfreq() selects timestamps that fall exactly on the grid. It does not combine data. If you have several readings per day, or timestamps with times of day, use resample("D") with an aggregation such as .sum() or .mean() first. Then lag the result.
Gaps inside groups
Panel data, such as many stores in one table, can have different gaps in each group. Regularize each group separately, then lag within groups. If you call asfreq() on the whole table, it works on one index and cannot do this.
df = pd.DataFrame({
"store": ["A", "A", "B", "B", "B"],
"date": pd.to_datetime(
["2024-01-01", "2024-01-03", "2024-01-01", "2024-01-02", "2024-01-03"]
),
"sales": [10, 15, 100, 90, 95],
})
daily = (
df.set_index("date")
.groupby("store")["sales"]
.resample("D")
.asfreq()
.reset_index()
)
daily["sales_lag1"] = daily.groupby("store")["sales"].shift(1)
print(daily) store date sales sales_lag1
0 A 2024-01-01 10.0 NaN
1 A 2024-01-02 NaN 10.0
2 A 2024-01-03 15.0 NaN
3 B 2024-01-01 100.0 NaN
4 B 2024-01-02 90.0 100.0
5 B 2024-01-03 95.0 90.0Store A was missing 2024-01-02, so the grid inserted a NaN row, and the lag for 2024-01-03 is NaN rather than store A's value from two days earlier. Each store is regularized over its own date range. If the groups must share one range, reindex each group to a common pd.date_range instead.
Common errors
- Duplicate timestamps.
asfreq()cannot reindex an axis that contains the same label twice and raises aValueError. Aggregate duplicates first, for example withgroupby(level=0).sum(). - Unsorted index. Sort with
sort_index()before regularizing or shifting. A positional shift on an unsorted index moves values in file order, not time order. - Wrong frequency. Using
"D"for weekday-only data creates weekendNaNrows that dilute later statistics. Choose the frequency that matches how your data is produced. - Forgetting the dtype change. Integer columns become floats once
NaNappears. Usefill_valueinasfreq()if you need to keep integers and zero is a valid fill. - Filling and shifting in the wrong order. Forward-filling before a lag can leak invented values into the feature. Decide on the fill first, and keep it consistent between training and prediction.
Summary of the workflow
- Sort the index and remove or aggregate duplicate timestamps.
- Check regularity with
pd.infer_freq()or by inspecting timestamp differences. - Choose a frequency that matches how the data is produced, such as
"D"or"B". - Regularize with
asfreq()orreindex(), per group for panel data. - Decide what a missing row means and fill only when that is justified.
- Apply
shift(), now meaning one step of your chosen frequency.
Exercise
A series has daily values for 2024-02-01, 2024-02-02, 2024-02-05 and 2024-02-06. You call s.shift(1) and read the lag for 2024-02-05 as "the previous day's value". What is wrong, and what is the fix if the data is calendar-daily? What would the lag for 2024-02-05 be after the fix?
Show answer
shift(1) moves by one row, so 2024-02-05 receives the value from 2024-02-02, which is three days earlier. Regularize with s.asfreq("D") first, which inserts rows for 2024-02-03 and 2024-02-04 as NaN. After asfreq("D").shift(1), the lag for 2024-02-05 is the value for 2024-02-04, which is NaN because it was not recorded.
Exercise
You have weekday-only closing prices. Why is asfreq("B") usually a better choice than asfreq("D") before computing a one-step lag, and what does the lag for a Monday contain in each case?
Show answer
With "B" there is no slot for Saturday or Sunday, so Monday's one-step lag is Friday's price. With "D", two NaN rows are inserted for the weekend, so Monday's lag is Sunday's value, which is NaN, and Friday's price is pushed to Saturday's lag. The "B" grid matches how the data is produced and avoids spurious NaN values.
Exercise
You need a one-day calendar lag for each row of an irregular series, but you must not add any rows. Which call do you use, and why does a row get NaN when its previous calendar day is absent?
Show answer
Assign s.shift(1, freq="D") to a new column. The call moves the index labels forward by one day and leaves the values unchanged. Assignment aligns on the index, so a row only receives a value if a label exists exactly one day earlier. If the previous day is absent, no shifted label matches and the row gets NaN.