Sub topic 1
A time series to work with: DatetimeIndex refresher
Every shift() example in this tutorial uses a Series or DataFrame whose index is a DatetimeIndex. This chapter covers how to build that index, which properties of it matter for shifting, and how to check it before you lag anything. It also defines the small sales Series that later chapters reuse.
Prerequisites
This chapter assumes you already have:
- Basic Python: functions, lists, dictionaries, and f-strings.
- Experience creating pandas Series and DataFrames, and selecting with
[]and.loc. - A first contact with
pd.date_range. You do not need to knowshift()yet.
The examples were written for pandas 2.x.
Why the index matters for shifting
shift() does not read dates. By default it moves values by a number of rows, and it leaves the index where it is. The index still matters, for three reasons:
- If the rows are not sorted by time, "one row back" is not "one period back".
- If timestamps are missing, one row back may be two days back.
- If the index has a known frequency,
shift()can move the labels instead of the values (thefreqargument, covered in a later chapter).
So the first job is to get a clean, sorted, time-aware index, and to know whether it has gaps.
Building a DatetimeIndex
A DatetimeIndex is a pandas index that stores timestamps (pd.Timestamp values) as 64-bit integers internally. It gives you date-aware slicing, calendar properties such as .year and .dayofweek, and an optional frequency.
From a regular range
pd.date_range creates evenly spaced timestamps. This is the Series used throughout the tutorial:
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)
print(type(s.index).__name__)
print(s.index.freq)The index type is DatetimeIndex, and s.index.freq is a daily offset. That attribute is the index's declared frequency. date_range always sets it.
You choose the length with either periods= or end=:
print(pd.date_range("2024-01-01", "2024-01-04", freq="D"))
print(pd.date_range("2024-01-01", periods=3, freq="MS"))The first call gives four days. The second gives the first day of three consecutive months (MS means month start).
From a column of strings
Real data usually arrives as text in a column. Convert it with pd.to_datetime, then move it into the index with set_index:
raw = pd.DataFrame({
"date": ["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-05"],
"sales": [10, 12, 11, 14],
})
raw["date"] = pd.to_datetime(raw["date"])
ts = raw.set_index("date")["sales"]
print(ts.index.dtype)
print(ts.index.freq)The dtype is a datetime64 type, so the index is time-aware. The frequency is None. set_index never infers or sets a frequency, even when the dates look regular. Here the dates also skip January 3, so there is no regular frequency to find.
If your strings are ambiguous, pass format= so pandas does not guess the day/month order:
print(pd.to_datetime(["03/04/2024"], format="%d/%m/%Y"))This prints April 3, 2024. Without format, pandas may read the same string as March 4.
For unparseable values, errors="coerce" turns them into NaT (not-a-time, the missing-value marker for timestamps) instead of raising an error. Use it with care. A NaT in the index will cause trouble later, so check for it and drop or repair those rows.
Summary of constructors
| Tool | Use it when | Sets `freq`? |
|---|---|---|
| `pd.date_range(...)` | You want to generate regular timestamps | Yes |
| `pd.to_datetime(...)` | You have strings or numbers to convert | No |
| `df.set_index("date")` | A datetime column should become the index | No |
| `obj.asfreq("D")` | You want a fixed frequency, with gaps filled as `NaN` | Yes |
The freq attribute
The freq attribute is easy to overlook, and it behaves in ways that surprise people. It describes the spacing the index is declared to have. It is not recomputed automatically from the timestamps.
print(s.index.freq) # a Day offset
print(s["2024-01-02":"2024-01-03"].index.freq) # slice keeps it
irregular = s.drop(pd.Timestamp("2024-01-03"))
print(irregular.index.freq) # None
print(pd.infer_freq(s.index)) # 'D'
print(pd.infer_freq(irregular.index)) # NoneThree rules cover most cases:
- Slicing a regular range keeps the frequency, because the result is still evenly spaced.
- Removing or filtering rows (
drop, boolean masks) setsfreqtoNone, because gaps may now exist. pd.infer_freq(index)looks at the actual timestamps and returns a frequency string, orNoneif there is no regular spacing. It needs at least three timestamps.
Here is the decision flow for preparing a series, which the rest of the tutorial follows:
Selecting by date
A DatetimeIndex accepts date strings in .loc. Partial strings select everything within that period:
print(s.loc["2024-01-02"]) # one value: 12
print(s.loc["2024-01-02":"2024-01-03"]) # two rows
print(s.loc["2024-01"]) # all of JanuaryTwo details are worth remembering:
- Slices on a label index include both endpoints.
"2024-01-02":"2024-01-03"returns both days, unlike a Python list slice. - A string such as
"2024-01"is treated as a period. It matches every timestamp inside January, not only midnight on the first.
Prefer .loc over bare s["2024-01"]. On a DataFrame, df["2024-01"] is read as a column lookup, so .loc is the form that works for both Series and DataFrames.
Slicing with date strings relies on the index being sorted. On an unsorted index, pandas may raise a KeyError or return surprising results. That is one more reason to sort first.
Calendar properties
A DatetimeIndex exposes the parts of each timestamp as attributes. They are useful for features and for checking your data:
print(s.index.year.tolist())
print(s.index.dayofweek.tolist()) # Monday is 0
print(s.index.day_name().tolist())The days of the week for the sample Series are Monday through Thursday, so dayofweek prints [0, 1, 2, 3].
You will use these later to see why shifting by one row differs from shifting by one calendar day. Weekends are the standard example. A business-day index skips Saturday and Sunday:
bdays = pd.date_range("2024-01-05", periods=4, freq="B")
print(bdays.day_name().tolist())The result is Friday, Monday, Tuesday, Wednesday. On this index, "one row back" from Monday is Friday, which is three calendar days earlier. Whether that is right depends on what you want to measure, and this is the question the later chapter on freq answers.
Checking the index before you shift
Make three checks a habit. The helper below collects them:
def check_index(obj):
idx = obj.index
return {
"is_datetime": isinstance(idx, pd.DatetimeIndex),
"sorted": bool(idx.is_monotonic_increasing),
"unique": bool(idx.is_unique),
"freq": idx.freq,
"inferred_freq": pd.infer_freq(idx) if len(idx) >= 3 else None,
}
print(check_index(s))
print(check_index(ts))For s, everything passes and the inferred frequency is 'D'. For ts, the index is a datetime, sorted and unique, but both freq and inferred_freq are None, because January 3 is missing. That tells you a row-based shift on ts would treat January 2 and January 4 as neighbors.
Unsorted data
Data exported from databases or merged from several files is often out of order:
shuffled = pd.Series(
[15, 10, 11, 12],
index=pd.to_datetime(
["2024-01-03", "2024-01-01", "2024-01-04", "2024-01-02"]
),
name="sales",
)
print(shuffled.index.is_monotonic_increasing) # False
fixed = shuffled.sort_index()
print(fixed.index.is_monotonic_increasing) # True
print(fixed.index.freq) # NoneAfter sort_index() the values line up with the correct days, but freq is still None, because sorting does not declare a frequency. If the dates are truly regular and you want the frequency recorded, call fixed.asfreq("D"). If dates are missing, asfreq also inserts them as NaN rows. A later chapter covers this in detail.
Duplicate timestamps
Two rows with the same timestamp make "the previous value" ambiguous. Detect them with is_unique, and decide how to combine them:
dup = pd.Series(
[1, 2, 3],
index=pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-02"]),
)
print(dup.index.is_unique) # False
print(dup.loc["2024-01-02"]) # returns two rows
print(dup.groupby(level=0).sum()) # one row per timestampWhether you sum, average, or keep the last value depends on what the numbers mean. For sales, summing is natural. For a price snapshot, keeping the last is more likely correct.
Common errors
- Dates left as strings. An index of
objectdtype sorts alphabetically, which is fine for ISO format (2024-01-02) but wrong for01/02/2024. It also has no.yearor.dayofweek, and no frequency tools. Always convert withpd.to_datetime. - Assuming
set_indexgives a frequency. It does not. Checkidx.freqandpd.infer_freq(idx). - Forgetting that filtering removes the frequency. After
df[df.sales > 10], row neighbors are no longer calendar neighbors. - Mixing time zones. A timezone-aware index (
tz_localize("UTC")) and a naive one cannot be compared or combined directly. Pick one convention for the whole dataset. - Using the date as a regular column. Lag logic is simpler and safer when the timestamp is the index, and group-wise lags later in this tutorial assume a clean time column.
What comes next
With a sorted, unique DatetimeIndex and a known frequency, you are ready for the main subject. The next chapter introduces shift(periods) on the Series s, and shows how each value moves one row forward in time. Keep check_index in your toolkit. Later chapters reuse the same checks when they deal with gaps, groups and leakage.
Exercise
You load a CSV with a date column of ISO strings and a sales column. You run df.set_index("date")["sales"] without converting date first. Name two things that no longer work as you expect, and give the fix.
Show answer
The index has object (string) dtype, not datetime64. Date-aware features fail or behave differently: there are no .year or .dayofweek properties, no frequency handling, and a later asfreq or shift(freq=...) will not work as intended. Slicing with partial dates may also fail, and non-ISO formats would sort alphabetically rather than chronologically. The fix is to convert first with df["date"] = pd.to_datetime(df["date"]), then call set_index("date"), and finally sort_index().
Exercise
A Series has a DatetimeIndex built by pd.date_range("2024-01-01", periods=5, freq="D"). You keep only rows where the value is above the mean, using a boolean mask. What is freq on the result, and why does it matter for shifting by one row?
Show answer
It is None. Filtering can remove days, so pandas no longer declares a regular spacing. This matters because a one-row shift on the filtered Series moves values between rows that may be more than one day apart. To restore calendar spacing, call asfreq("D") on the result, which re-inserts the missing days as NaN.
Exercise
What do idx.is_monotonic_increasing, idx.is_unique and pd.infer_freq(idx) each tell you, and what would you do if each one gave a bad result?
Show answer
is_monotonic_increasing is False when the timestamps are out of order, so call sort_index(). is_unique is False when timestamps repeat, so aggregate (for example groupby(level=0).sum()) or drop duplicates. pd.infer_freq(idx) returns None when the spacing is irregular, so regularize with asfreq (or reindex onto a full date_range) before using row-based shifts.