简体   繁体   中英

Why does Pandas rolling mean centres the window

I want to create a graph of annual data and a 5 year moving average, comprising the current and previous 4 years values. However my 5 year window is centred and I cant figure out why. By that I mean the first moving average starts in the 3 year, and the final value is in the 3rd last year. With my data, the moving average falls of a cliff because the final year is incomplete - I had anticipated dropping the final value also, but I cant figure out how to get the moving average to work as intended.

My code is below

#Plot historical revenue for context. Drop last year as it is incomplete
data=df_full.groupby('year').agg(Revenue=('price',sum)).reset_index()
data=data[:-1]
dataMA=df_full.groupby('year').agg(Revenue=('price',sum)).reset_index().rolling(5,center=False).mean()

fig=go.Figure()
fig.add_trace(go.Scatter(x=data.year, y=data.Revenue, name="Revenue"))
fig.add_trace(go.Scatter(x=dataMA.year, y=dataMA.Revenue, name="5 year Average"))
fig.update_layout(title="Annual Revenue 2001 to 2019",
                  xaxis_title="Year",
                  yaxis_title="Annual Revenue $")
fig.show()

I tried adding "centre=False", but this made no difference. The graph still looks like below.

在此处输入图片说明

See, it is supposed to work. Since, I don't have your dataset how it looks — I created myself

ser = pd.Series(np.random.randint(10,1000, 19), index=range(2001, 2020))

# Should look like this after your Group by
2001    578
2002    388
2003    803
2004    413
2005    125
2006    331
2007    179
2008    180
2009    331
2010    875
2011    422
2012    699
2013    256
2014    918
2015    566
2016    754
2017    521
2018    200
2019     16
dtype: int32

Now, doing the rolling:

ser.plot()
plt.ylim([0, df.max()])
ser.rolling(5, center=False).mean().plot()
plt.xticks(range(2000, 2020, 5));

The result is: 在此处输入图片说明

Now I think

You should get your data in the simple form like shown just above and store in the variable first — instead of stacking up all operations all together making one long line.

Then try the same. It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM