shift(), diff() and pct_change()
Many questions about ordered data compare a row with the row before it. How much did the price change since yesterday? What's the growth rate month over month? How long since the previous visit? pandas answers these with three small methods.
| Method | Returns |
|---|---|
shift(n) |
the values moved down by n rows (up if negative) |
diff(n) |
the value minus the value n rows earlier |
pct_change(n) |
the relative change from n rows earlier |
shift()
import pandas as pd
price = pd.Series([102.0, 104.5, 103.0, 108.2, 107.5],
index=pd.date_range("2024-09-02", periods=5, freq="B"), name="close")
print(pd.DataFrame({
"close": price,
"previous": price.shift(1),
"next": price.shift(-1),
})) close previous next
2024-09-02 102.0 NaN 104.5
2024-09-03 104.5 102.0 103.0
2024-09-04 103.0 104.5 108.2
2024-09-05 108.2 103.0 107.5
2024-09-06 107.5 108.2 NaN
shift(1) pushes every value one row down; the first row has no predecessor and becomes NaN. shift(-1) looks one row ahead. The index itself doesn't move.
diff() and pct_change()
diff() is shorthand for s - s.shift(), and pct_change() for s / s.shift() - 1:
import pandas as pd
price = pd.Series([102.0, 104.5, 103.0, 108.2, 107.5],
index=pd.date_range("2024-09-02", periods=5, freq="B"), name="close")
table = pd.DataFrame({
"close": price,
"change": price.diff(),
"pct": (price.pct_change() * 100).round(2),
})
print(table)
print("Best day:", table["pct"].idxmax().date()) close change pct
2024-09-02 102.0 NaN NaN
2024-09-03 104.5 2.5 2.45
2024-09-04 103.0 -1.5 -1.44
2024-09-05 108.2 5.2 5.05
2024-09-06 107.5 -0.7 -0.65
Best day: 2024-09-05
Comparing with a fixed lag
The argument says how many rows back to look. With monthly data, diff(12) compares each month with the same month a year earlier, which removes seasonal effects:
import pandas as pd
months = pd.period_range("2023-01", "2024-06", freq="M")
signups = pd.Series([50, 48, 60, 72, 80, 95, 110, 104, 85, 70, 62, 90,
58, 55, 71, 80, 93, 108], index=months, name="signups")
yoy = pd.DataFrame({
"signups": signups,
"year_ago": signups.shift(12),
"yoy_pct": (signups.pct_change(12) * 100).round(1),
})
print(yoy.tail(6)) signups year_ago yoy_pct
2024-01 58 50.0 16.0
2024-02 55 48.0 14.6
2024-03 71 60.0 18.3
2024-04 80 72.0 11.1
2024-05 93 80.0 16.3
2024-06 108 95.0 13.7
Time between events
diff() also works on datetimes, giving the gap since the previous row. Combined with groupby, it computes the gap per customer:
import pandas as pd
visits = pd.DataFrame({
"customer": ["ann", "ben", "ann", "ann", "ben"],
"date": pd.to_datetime(["2024-03-01", "2024-03-04", "2024-03-15", "2024-04-02", "2024-04-20"]),
})
visits["days_since_last"] = visits.groupby("customer")["date"].diff().dt.days
print(visits)
print(visits.groupby("customer")["days_since_last"].mean()) customer date days_since_last
0 ann 2024-03-01 NaN
1 ben 2024-03-04 NaN
2 ann 2024-03-15 14.0
3 ann 2024-04-02 18.0
4 ben 2024-04-20 47.0
customer
ann 16.0
ben 47.0
Name: days_since_last, dtype: float64
Each customer's first visit has no previous visit, so its gap is NaN; the mean skips it.
Detecting changes
Comparing a column with its shifted self finds the rows where something changed, useful for spotting status transitions:
import pandas as pd
status = pd.Series(["ok", "ok", "warn", "warn", "ok", "down", "down", "ok"],
index=[f"{h:02d}:00" for h in range(8)])
changed = status != status.shift()
print(status[changed])
print("Number of state changes:", changed.sum() - 1)00:00 ok
02:00 warn
04:00 ok
05:00 down
07:00 ok
dtype: object
Number of state changes: 4
The first row always counts as "changed" (it differs from NaN), which is why we subtract 1.
Test yourself
What is pd.Series([10, 15, 12]).diff().to_list()?
- [5, -3]
- [nan, 5.0, -3.0]
- [10, 5, -3]
- [nan, 15, 12]
What does pct_change() return for values 50 then 60?
- 10
- 0.2
- 1.2
- 20
Which call gives each row the value from the NEXT row?
- shift(1)
- shift(-1)
- diff(-1)
- next()