Sub topic 1
A time series to work with: DatetimeIndex refresher
Prerequisites
This chapter assumes you know:
- Basic Python, including functions and printing results.
- How to create and index pandas Series and DataFrames with
[]and.loc. - What
pd.date_rangedoes at a basic level.
Every later chapter in this tutorial uses shift(), and shift() is only reliable when the index is in good shape. This chapter builds the small series used throughout and shows how to check that index.
Why the index matters for shifting
shift() moves values by position. It does not look at the dates. If the index is unsorted, has duplicates, or is missing days, "the previous row" may not be "the previous day". Checking the index first prevents most shifting bugs.
A DatetimeIndex is a pandas index whose labels are timestamps. It gives you date-aware slicing, a frequency attribute, and the checks below.
The running example
Create a daily series of four sales values. Later chapters reuse this series as s.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
print(s)The output is:
2024-01-01 10
2024-01-02 12
2024-01-03 15
2024-01-04 11
Freq: D, Name: sales, dtype: int64The line Freq: D shows that the index has a daily frequency. The freq attribute is metadata. pd.date_range sets it, but pandas does not enforce it after later operations.
Checking the index before you shift
Three properties decide whether row-based shifting means what you expect.
print(s.index.is_monotonic_increasing) # True: dates run oldest to newest
print(s.index.is_unique) # True: no repeated timestamps
print(s.index.inferred_freq) # 'D': pandas detects a daily spacing| Check | What it tells you | Problem if it fails |
|---|---|---|
| `is_monotonic_increasing` | Rows are in time order | A lag takes a value from a later date |
| `is_unique` | Each timestamp appears once | Several rows share one date, so "previous" is ambiguous |
| `inferred_freq` | Dates are evenly spaced | Missing dates make one row back span more than one period |
inferred_freq returns None when the spacing is irregular. It needs at least three timestamps to infer anything.
Common errors
Dates stored as strings
Dates read from a CSV file are usually plain strings. An index of strings has the object dtype, and it has no date features. Convert the column, set it as the index, and sort.
raw = pd.DataFrame({
"date": ["2024-01-03", "2024-01-01", "2024-01-02"],
"sales": [15, 10, 12],
})
raw["date"] = pd.to_datetime(raw["date"])
ts = raw.set_index("date").sort_index()["sales"]
print(type(ts.index).__name__) # DatetimeIndex
print(ts.index.is_monotonic_increasing) # TrueSorting matters here. The rows arrived out of order, and shift() would have used that order.
Missing dates
Drop one day from the running series and look at the index again.
gappy = s.drop(pd.Timestamp("2024-01-03"))
print(gappy.index.inferred_freq) # None
print(gappy.index.is_monotonic_increasing) # TrueThe index is still sorted, but the spacing is no longer even. Row-based shifting now moves 2024-01-04 back to 2024-01-02, which is two days. The chapter on missing timestamps shows how asfreq() fixes this.
Duplicate timestamps
Two rows with the same date usually come from merged files or from several records per day. Check with s.index.is_unique. If it is False, aggregate first, for example with s.groupby(level=0).sum(), or decide which duplicate to keep. Do not shift until each timestamp appears once, unless you are lagging within groups, which a later chapter covers.
What comes next
With the running series s in place and the index checks understood, the next chapter calls shift(1) and looks at what it returns.
Exercise
You load a CSV with columns "day" and "units", where "day" holds strings such as "2024-03-05". The rows are not in date order. List the steps you take before calling shift(1) on "units", and name the property you check at the end.
Show answer
Convert with df["day"] = pd.todatetime(df["day"]), then set the index with df = df.setindex("day"), then sort with df = df.sortindex(). Finally check df.index.ismonotonicincreasing (it should be True). You should also check df.index.isunique and df.index.inferred_freq so that duplicates and missing dates do not make "one row back" differ from "one period back".