Sub topic 5
Period-over-period change: shift(), diff() and pct_change()
This chapter assumes you can create a Series with a DatetimeIndex, that you know what shift(1) and shift(-1) do, and that you know why shift() leaves NaN at one edge. Here you will use that knowledge to measure change from one period to the next. You will also see where the shortcuts diff() and pct_change() agree with a manual shift() and where they differ.
The three ways to measure change
A period-over-period change compares each value with an earlier one. The same calculation can be written three ways:
- Manual:
s - s.shift(1)for the absolute change, ands / s.shift(1) - 1for the relative change. s.diff(): the absolute change.s.pct_change(): the relative change, as a fraction (0.25 means +25%).
All three start from the same idea. Line up each row with the row n positions earlier, then subtract or divide. We use the same small series throughout.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
change = s - s.shift(1)
print(change)
print(change.equals(s.diff())) # True
print(s.pct_change())The absolute change is NaN, 2.0, 3.0, -4.0. The relative change is NaN, 0.2, 0.25, -0.266667. The first row is NaN in every version because there is no earlier row to compare against.
What each tool does internally
diff() is s - s.shift(periods). pct_change() is s / s.shift(periods) - 1, with extra handling for missing values (see below). Neither method looks at the index labels. They count rows, exactly as shift(periods) does without freq.
| Task | Manual form | Shortcut |
|---|---|---|
| Absolute change | `s - s.shift(n)` | `s.diff(n)` |
| Relative change | `s / s.shift(n) - 1` | `s.pct_change(n)` |
| Forward change (next minus current) | `s.shift(-n) - s` | `-s.diff(-n)` |
| Change since a fixed baseline | `s - s.iloc[0]` | none |
Two behaviors are worth knowing before you rely on the shortcuts.
diff()always returns floats for integer input, because the first row becomesNaN. The same is true forshift()withoutfill_value.- The shortcuts accept a
periodsargument, so a longer comparison needs no extra code.
print(s.diff(2)) # NaN, NaN, 5.0, -1.0
print(s.pct_change(2)) # NaN, NaN, 0.5, -0.083333diff(2) compares each day with two days earlier. For weekly data, diff(52) would compare each week with the same week a year earlier, provided the series has no gaps and every year has 52 rows.
Choosing between shift() and the shortcuts
Use diff() and pct_change() when you want the standard calculation. Use the manual shift() form when you need to change something about it. Typical reasons are:
- You want to keep the lagged value as its own column, for example to show "previous" next to "current".
- You need a custom ratio, such as a log return, which is
np.log(s / s.shift(1)). - You want to control missing values without relying on a version-dependent default.
Keeping the lag as a column makes the arithmetic easy to inspect:
frame = s.to_frame()
frame["previous"] = s.shift(1)
frame["abs_change"] = frame["sales"] - frame["previous"]
frame["pct_change"] = frame["sales"] / frame["previous"] - 1
print(frame)If a result looks wrong, you can read previous directly and check which row was compared.
Forward change and the direction of the sign
s.diff() answers "how much did the value change to reach today?". Sometimes you want the opposite: "how much will it change by tomorrow?". Pass a negative period to diff(), or shift in the other direction manually.
print(s.diff(-1)) # -2.0, -3.0, 4.0, NaN (today minus tomorrow)
print(s.shift(-1) - s) # 2.0, 3.0, -4.0, NaN (tomorrow minus today)These two results have opposite signs, because diff(-1) still computes "current minus the shifted value". Choose one convention and name your columns clearly, for example sales_next_change.
Missing values: NaN at the edge and inside the data
The first n rows are NaN for a change of n periods. You can leave them as NaN, drop them with dropna(), or use fill_value in the manual form.
manual = s - s.shift(1, fill_value=0)
print(manual) # 10, 2, 3, -4 (integer dtype)This keeps integer dtype, but it also invents a "change" of 10 on the first day, as if sales had been zero before. Filling the edge with 0 only makes sense when zero is the true starting state. In most analyses, a missing first change is the more honest result.
NaN values in the middle of the data matter more. A NaN in the input produces NaN in two rows of the output: the row that holds the gap and the row after it, which compares against the gap.
irregular = s.drop(pd.Timestamp("2024-01-03"))
regular = irregular.asfreq("D")
print(irregular.diff()) # NaN, 2.0, -1.0
print(regular.diff()) # NaN, 2.0, NaN, NaNThe two results are different, and only the second one is correct. irregular has no row for January 3, so its diff() compares January 4 with January 2. It reports -1.0 as a one-day change when it spans two days. After asfreq("D"), the missing day is an explicit NaN, and the changes that depend on it are NaN as well. This is the same lesson as the previous chapter on gaps: diff() counts rows, so the rows must represent equal time steps.
print(regular.pct_change(fill_method=None))
# NaN, 0.2, NaN, NaNPosition versus label: the freq argument
pct_change() accepts a freq argument, which makes it compare against the value from a given time offset instead of a given number of rows. This works like shift(freq=...): the labels move, and values are matched by date. diff() has no freq argument. If you need label-based absolute change on an irregular series, the most direct approach is still to regularize with asfreq() first and then call diff().
For data that is already regular, position-based and label-based methods give the same answer, and the simpler positional form is easier to read. For irregular data, regularize first, then use positions. That keeps your code simple and puts the handling of missing timestamps in one visible step.
Changes within groups
A table that holds several entities, such as stores or sensors, needs the same care as lags did. A plain df["sales"].diff() compares the first row of store B with the last row of store A. Group first, then compute the change.
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"date": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"] * 2),
"sales": [10, 12, 15, 100, 90, 95],
})
df = df.sort_values(["store", "date"])
grouped = df.groupby("store")["sales"]
df["sales_diff"] = grouped.diff()
df["sales_pct"] = grouped.pct_change(fill_method=None)
print(df)The results are:
| store | date | sales | sales_diff | sales_pct |
|---|---|---|---|---|
| A | 2024-01-01 | 10 | NaN | NaN |
| A | 2024-01-02 | 12 | 2.0 | 0.200000 |
| A | 2024-01-03 | 15 | 3.0 | 0.250000 |
| B | 2024-01-01 | 100 | NaN | NaN |
| B | 2024-01-02 | 90 | -10.0 | -0.100000 |
| B | 2024-01-03 | 95 | 5.0 | 0.055556 |
Each store starts with its own NaN. Without the grouping, store B would start with 100 - 15 = 85, which is a jump that never happened. The sort before grouping matters too, because grouped methods use the row order within each group, not the dates.
Common mistakes
- Comparing rows when you meant to compare dates.
diff()andpct_change()with an integer period count rows. If the index has gaps, the result silently spans a longer time. - Reading
pct_change()as a percentage. It returns a fraction. Multiply by 100 to report percent. - Dividing by zero or near-zero. If the previous value is
0, the manual ratio isinf(orNaNfor0 / 0). Check withnp.isinfor replace infinities before using the column in a model. - Using relative change on values that cross zero or can be negative. A move from
-5to-10gives+1.0frompct_change(), which reads as growth although the value fell. Prefer absolute change for such series. - Forgetting the sort order. If the index is not monotonic,
shift(),diff()andpct_change()all use the stored row order, not the time order. Callsort_index()first. - Averaging percentage changes over time. Mean of
pct_change()is not the compound growth rate. Use(last / first) ** (1 / n) - 1for compound growth overnperiods.
Summary of behavior
| Behavior | `shift(n)` | `diff(n)` | `pct_change(n)` |
|---|---|---|---|
| Compares rows by | position | position | position (or label with `freq`) |
| First `n` rows | `NaN` or `fill_value` | `NaN` | `NaN` |
| Integer input returns | float, unless `fill_value` is given | float | float |
| Gap handling | none | none | depends on `fill_method` |
| Works per group | with `groupby` | with `groupby` | with `groupby` |
Exercise
A daily series has rows for January 1, 2, 4 and 5 (January 3 is missing) with values 10, 12, 11, 15. You call s.diff() directly and get a change of -1.0 on January 4. Explain why this is misleading. Then write the code that gives correct one-day changes, and state what values you get for January 4 and January 5.
Show answer
diff() counts rows, so January 4 is compared with January 2, a two-day gap, and the result is reported as a one-day change. Regularize first with s.asfreq("D").diff(). That inserts January 3 as NaN, so the changes are NaN (Jan 1), 2.0 (Jan 2), NaN (Jan 3), NaN (Jan 4, because its previous day is missing) and 4.0 (Jan 5, 15 - 11).