Sub topic 2
Period-over-period change: `shift()`, `diff()` and `pct_change()`
Assume you know basic Python, pandas Series and DataFrames, and DatetimeIndex. In a time series, a period-over-period change compares each value with an earlier value.
Comparing each value with the previous one
shift(1) moves values down by one row. The first row has no previous value, so it becomes NaN. diff() calculates the subtraction for you. pct_change() calculates the relative change.
import pandas as pd
sales = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
previous = sales.shift(1)
change = sales - previous
print(previous)
print(change)
print(sales.diff())
print(sales.pct_change())The results of change and sales.diff() are equal. The percentage change is expressed as a decimal. For example, a change from 10 to 12 is 0.2, or 20%.
A negative period creates a lead. sales.shift(-1) places the next row beside the current row. This is useful for analysis, but it can leak future information into a forecasting model.
Position versus index frequency
By default, shift() moves values by row position. With freq, it moves the index labels while leaving the values in their original order.
moved_labels = sales.shift(1, freq="D")
print(moved_labels)Here, every date moves one calendar day forward, but no value is discarded and no NaN is created.
Regularizing missing timestamps
A row shift means “previous row,” not always “previous calendar day.” If dates are missing, first create a regular frequency with asfreq().
irregular = sales.drop(pd.Timestamp("2024-01-03"))
regular = irregular.asfreq("D")
print(regular)
print(regular.shift(1))asfreq("D") inserts the missing date with NaN. The subsequent shift now represents the previous calendar day. Decide whether to fill that inserted value before calculating changes.
Exercise
Which method moves index labels without moving the values?
Show answer
Use shift() with the freq argument, such as sales.shift(1, freq="D").