Change Over Time

Differences and growth rates, and the row that has neither.

shift compares a row with its neighbour

diff is the difference from the previous row and pct_change is that as a proportion. Both leave the first row empty, because it has nothing before it.

import pandas as pd

s = pd.Series([100, 110, 99])
print(s.diff().tolist())
print(s.pct_change().round(3).tolist())

A percentage needs a base

Growth from zero is undefined, and pandas says so with an infinity rather than a number. Deciding what to show for that case is part of the analysis.

import pandas as pd

s = pd.Series([0, 5])
print(s.pct_change().tolist())

Exercise

Try It Yourself

Write rises(s) that returns how many times the value went up compared with the row before it.

Press Run to see output

Check Your Understanding