Sub topic 7
Missing Timestamps: Regularize with asfreq() Before Shifting
This chapter assumes you know basic Python, how to build a pandas Series with a DatetimeIndex, and how shift(periods) works. If any of that is unfamiliar, review the earlier chapters first.
Why shift() can give a wrong answer without raising an error
shift(1) moves values by row position. It does not look at the dates. If every day has a row, one row back is one day back. If a day is missing, one row back can be two days back or more. The result looks fine, but a "previous day" feature then contains values from the wrong day.
Here is a daily series with January 3 removed:
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.shift(1))The output is:
2024-01-01 NaN
2024-01-02 10.0
2024-01-04 12.0
Name: sales, dtype: float64January 4 shows 12, which is the value from January 2. The real previous day, January 3, has no data. The result has no NaN to warn you, so the error is silent.
Regularize the index with asfreq()
asfreq(freq) rebuilds the index as a complete, evenly spaced range from the first timestamp to the last. Timestamps that were absent are added as rows with NaN. After that, one row is one period, and shift means what you expect.
regular = irregular.asfreq("D")
print(regular)
print(regular.shift(1))regular now has four rows, and January 3 is NaN. Shifting it by one gives:
2024-01-01 NaN
2024-01-02 10.0
2024-01-03 12.0
2024-01-04 NaN
Name: sales, dtype: float64January 4 now has NaN as its lag, because January 3 is unknown. This is the honest answer. January 3 also gets a correct lag of 12.
The dtype changes from integer to float because integers cannot hold NaN. That is expected.
Deciding what to do with the new NaN rows
asfreq only makes the gaps visible. You then choose how to treat them. The right choice depends on what the data means.
| Goal | Option | Example |
|---|---|---|
| Keep the gap as unknown | Do nothing | `irregular.asfreq("D")` |
| Missing means zero (for example, no sales) | `fill_value` | `irregular.asfreq("D", fill_value=0)` |
| Carry the last known value forward | `method="ffill"` | `irregular.asfreq("D", method="ffill")` |
fill_value only applies to rows that asfreq adds. It does not replace NaN values that were already in your data.
Filling with 0 is correct for counts such as daily orders, where no row means no orders. It is wrong for a measurement such as temperature. Forward-filling suits a state that persists, such as a price. Decide this deliberately, because the choice changes your lags.
zero_filled = irregular.asfreq("D", fill_value=0)
print(zero_filled.shift(1))Here January 4 gets a lag of 0, which matches the "no sales on January 3" interpretation. The dtype stays integer because no NaN is introduced.
Common errors
- Duplicate timestamps.
asfreqraises aValueErrorif the index contains duplicates, because it cannot decide which row to keep. Remove or aggregate duplicates first. - Unsorted index. Sort with
sort_index()first. Bothasfreqandshiftassume time order. - Timestamps off the grid.
asfreq("D")builds midnight-aligned dates. A row stamped2024-01-02 10:30does not match any of them and is dropped. If your data has intraday times, useresample("D").sum()or another aggregation to move to a daily grid.asfreqonly selects and inserts. It never aggregates. - Wrong frequency string.
"D"is calendar days. For business days use"B". A weekend gap in a business-day series is then not a missing value, and the shift skips it correctly. - Grouped data. For several stores or sensors, regularize each group separately, then shift within each group. The next chapter covers the grouped shift.
Summary of the workflow
- Sort the index and remove duplicate timestamps.
- Call
asfreqwith the frequency that matches how the data should be spaced. - Decide how to handle the inserted rows: leave NaN, fill with a constant, or forward-fill.
- Call
shift, which now means "one period earlier."
Exercise
A daily series has rows for Jan 1, Jan 2 and Jan 5 only. You call s.shift(1) and the Jan 5 row shows the Jan 2 value. Why is this misleading, and what do you change so that Jan 5 shows NaN, and the Jan 3, Jan 4 and Jan 5 rows follow calendar days?
Show answer
shift(1) moves by row position, so "one row back" for Jan 5 is Jan 2, which is three days earlier, not one. Call s.asfreq("D") first. It inserts rows for Jan 3 and Jan 4 with NaN. Then shift(1) gives Jan 3 = Jan 2's value, Jan 4 = NaN (Jan 3 is unknown), and Jan 5 = NaN (Jan 4 is unknown).