0

I need to find the average ratio in a window of 5 years of a DataFrame. If I do:

df = pd.DataFrame({'Cost': {0: 0.0,  13: 70.0,  30: 132.0,  53: 2.0,  71: 69.0,  90: 71.0,  107: 57.0,  128: 55.0,  151: 57.0},
       'YEAR': {0: 2008,  13: 2009,  30: 2010,  53: 2011,  71: 012,  90: 2013,  107: 2014,  128: 2015,  151: 2016}})

and then

df["Cost"].rolling(window=5, min_periods=5,center=True).sum() / df["Cost"].rolling(window=5, min_periods=5,center=True).sum().sum()

i can get it but if there's more rows, i get too many years. How can i get the mean cost ratio for 5 years?

The return should be an array of 5 that sums up to 1.0 as my current line of code does:

[0.19017704,0.2307253 ,  0.22330097,  0.1793261 ,  0.17647059]
TobSta
  • 766
  • 2
  • 10
  • 29

1 Answers1

2

You may change you sum to mean

df["Cost"].rolling(window=5, min_periods=5,center=True).mean()

Update

using rolling_window

s=rolling_window(df.Cost.values,5)
s/np.sum(s,1)
array([[0.        , 0.20348837, 0.39879154, 0.00787402, 0.22330097],
       [0.25641026, 0.38372093, 0.0060423 , 0.27165354, 0.22977346],
       [0.48351648, 0.00581395, 0.20845921, 0.27952756, 0.18446602],
       [0.00732601, 0.2005814 , 0.21450151, 0.22440945, 0.17799353],
       [0.25274725, 0.20639535, 0.17220544, 0.21653543, 0.18446602]])
BENY
  • 317,841
  • 20
  • 164
  • 234