Sub topic 5
Period-over-period change: shift(), diff() and pct_change()
This chapter assumes you can build a Series with a DatetimeIndex and that you know what shift(1) does to values and to the first row. Here you will use that shifted copy to measure change from one period to the next.
The working model
A period-over-period change compares each row with the row before it. Shifting by one row lines up each value with its predecessor, so you can subtract or divide the two.
- Absolute change:
s - s.shift(1) - Relative change:
s / s.shift(1) - 1
pandas wraps both patterns in diff() and pct_change().
import numpy as np
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
manual_diff = s - s.shift(1)
print(manual_diff.equals(s.diff()))
manual_pct = s / s.shift(1) - 1
print(np.allclose(manual_pct.dropna(), s.pct_change().dropna()))
print(s.diff())
print(s.pct_change())The diff() result is NaN, 2.0, 3.0, -4.0. The pct_change() result is NaN, 0.20, 0.25, -0.266667. The first row is NaN in both because it has no earlier row to compare with. The result is float even though sales is integer, because NaN cannot be stored in an integer column.
Choosing between the three
| Tool | Formula | Use it when |
|---|---|---|
| `s - s.shift(n)` | value minus earlier value | You also need the shifted column for something else |
| `s.diff(n)` | same as above | You only need the change |
| `s.pct_change(n)` | value / earlier value - 1 | You want growth rates that are comparable across scales |
All three accept a number of rows, n. The default is 1.
Comparing over longer distances
Pass a larger periods value to compare with a row further back. On daily data, 7 gives week-over-week change. On monthly data, 12 gives year-over-year change.
daily = pd.Series(
[10, 12, 15, 11, 13, 14, 16, 18, 17, 19, 21, 20, 22, 25],
index=pd.date_range("2024-01-01", periods=14, freq="D"),
name="sales",
)
week_over_week = daily.pct_change(periods=7)
print(week_over_week.dropna())The first seven rows are NaN, and the first valid value is 18 / 10 - 1 = 0.8. A comparison with the same weekday removes the weekly cycle that a one-day change would mix into the result.
Common errors
Counting rows instead of time
diff(7) means seven rows back. If the index has missing dates, seven rows may span eight or more days, and the result is wrong without any warning. Regularize first with asfreq(), as covered in the chapter on missing timestamps:
regular = daily.drop(pd.Timestamp("2024-01-03")).asfreq("D")
print(regular.diff())The restored date appears as NaN. The change into that date and the change out of it are both NaN, which is honest, because the true value is unknown.
Hidden filling in pct_change
Before pandas 3.0, pct_change() forward-fills NaN values by default before computing, so a gap can silently produce a change of 0. Recent 2.x versions deprecate this behavior. Pass fill_method=None to turn it off in every version:
print(regular.pct_change(fill_method=None))Zero and negative bases
If the earlier value is 0, pct_change() returns inf (or -inf). If the earlier value is negative, the sign of the percentage is misleading, because going from -10 to -5 gives -0.5 even though the value rose. For such data, prefer diff().
Changes inside groups
On a DataFrame with several stores or tickers, df["sales"].diff() computes the first row of store B against the last row of store A. Group first, as in the grouped-lag chapter:
df = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"date": pd.to_datetime(["2024-01-01", "2024-01-02"] * 2),
"sales": [10, 12, 100, 90],
}).sort_values(["store", "date"])
df["change"] = df.groupby("store")["sales"].diff()
print(df)Each store now starts with NaN, and store B's change is -10.0.
Exercise
A monthly sales Series m has a complete, sorted month-start index. Write one expression for year-over-year percentage change that never forward-fills missing values. What will the first 12 results be?
Show answer
m.pct_change(periods=12, fill_method=None). The first 12 results are NaN, because those months have no value 12 rows earlier to compare with.