Here is a completely vectorized solution using pure pandas (in other words: it is fast).
It is relatively straightforward if you have a DataFrame with the proper index. Also, your value "INFLATION" is in undefined units. In order to match your example, I have to divide it by 10 (so it is neither fraction nor percentage).
Step 1: sample data as reproducible example
df = pd.DataFrame({
'TIME': ['2022-01', '2022-02', '2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08',
'2022-09', '2022-10', '2022-11', '2023-01', '2023-02', '2023-03', '2023-04'],
'A': [100, 120, 150, 140, 180, 200, 100, 120, 150, 140, 180, 200, 100, 120, 150],
'INFLATION': [0.3, 0.5, 0.4, 0.7, 0.6, 0.3, 0.5, 0.4, 0.7, 0.6, 0.3, 0.5, 0.8, 0.4, 0.1],
})
Step 2: Your calculation
- Convert the time column into a
PeriodIndex
df = df.assign(TIME=df['TIME'].apply(pd.Period)).set_index('TIME')
- Solution
ci = (1 + df['INFLATION']/10).cumprod() # cumulative inflation
ci12 = ci / ci.shift(12, 'M') # 12-month variation
x = df['A'].shift(12, 'M') * ci12
real_var = (df['A'] - x) / x # your "real variation"
# putting it all together in a new df
res = df.assign(ci12=ci12, x=x, real_var=real_var)
>>> res
A INFLATION ci12 x real_var
TIME
2022-01 100 0.3 NaN NaN NaN
2022-02 120 0.5 NaN NaN NaN
2022-03 150 0.4 NaN NaN NaN
2022-04 140 0.7 NaN NaN NaN
2022-05 180 0.6 NaN NaN NaN
2022-06 200 0.3 NaN NaN NaN
2022-07 100 0.5 NaN NaN NaN
2022-08 120 0.4 NaN NaN NaN
2022-09 150 0.7 NaN NaN NaN
2022-10 140 0.6 NaN NaN NaN
2022-11 180 0.3 NaN NaN NaN
2023-01 200 0.5 1.708788 170.878849 0.170420
2023-02 100 0.8 1.757611 210.913323 -0.525872
2023-03 120 0.4 1.757611 263.641653 -0.544837
2023-04 150 0.1 1.659053 232.267475 -0.354193