Compute fractional or percentage changes between current and prior elements across Series and DataFrames using the pct_change() method. Track financial growth, calculate period-over-period variations, and configure lag periods.
pct_change() method calculates the fractional change between the current element and a prior element (determined by the periods parameter). By default, it computes the change relative to the immediately preceding row (`periods=1`). The first row naturally results in `NaN`.import pandas as pd
prices = pd.Series([100, 110, 105, 126], name="PRICE")
print(prices)
assert prices.shape == (4,)
Expected output
0 100
1 110
2 105
3 126
Name: PRICE, dtype: int64
pct_change() on the Series to compute fractional changes relative to the prior row.chg = prices.pct_change()
print(chg)
assert chg.iloc[1] == 0.1
Expected output
0 NaN
1 0.1
2 -0.045455
3 0.2
Name: PRICE, dtype: float64
periods parameter to compute changes across multiple rows (e.g., comparing current values against two periods prior).chg_lag = prices.pct_change(periods=2)
print(chg_lag)
assert chg_lag.iloc[2] == 0.05
Expected output
0 NaN
1 NaN
2 0.05
3 0.145455
Name: PRICE, dtype: float64
rev = pd.Series([1000, 1200, 1500], name="REV"), compute the percentage change using default periods and verify that the final growth rate equals 0.25.pct_change().rev = pd.Series([1000, 1200, 1500], name="REV")
answer = rev.pct_change()
print(answer)
assert answer.iloc[2] == 0.25
Expected output
0 NaN
1 0.2
2 0.25
Name: REV, dtype: float64
Practice pct_change() examples interactively directly in your browser:
Reference: Pandas pct_change() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.