import pandas as pd s = pd.Series([100, 120, 144, 172.8]) result = s.pct_change() print(result)
The pct_change() function returns the percentage change between the current and previous element. The first element has no previous element, so it is NaN. The changes are calculated as (new - old) / old, so 120 to 100 is (120-100)/100 = 0.20 or 20%.
import pandas as pd df = pd.DataFrame({'value': [10, 15, 20, 30, 45]}) result = df['value'].pct_change(periods=2) print(result)
With periods=2, pct_change() computes the percentage change relative to the value two periods prior: (current - value_two_periods_ago) / value_two_periods_ago.
Calculations:
- Index 0: NaN
- Index 1: NaN
- Index 2: (20 - 10) / 10 = 1.0
- Index 3: (30 - 15) / 15 = 1.0
- Index 4: (45 - 20) / 20 = 1.25
This matches option A.
import pandas as pd s = pd.Series([1, 2, 3, 4]) result = s.pct_change(periods='two') print(result)
The periods parameter must be an integer. Passing a string like 'two' causes a ValueError.
import pandas as pd df = pd.DataFrame({'close': [100, 105, 110, 121, 115]})
pct_change() calculates the percentage change. The first value is NaN because there is no previous day. Filling NaN with 0 is common to indicate no return on first day.
Option C leaves NaN as is. Option C calculates absolute difference, not percentage. Option C calculates ratio times 100, which is not the percentage change.
fill_method='ffill' fills missing values forward before computing percentage change. This reduces NaNs in the result because missing data is replaced by the last valid value.