简体   繁体   中英

calculating moving average in pandas

So, this is fairly a new topic for me and I don't quite understand it yet. I wanted to make a new column in a dataset that contains the moving average of the volume column. The window size is 5 and moving average of row x is calculated from rows x-2, x-1, x, x+1, and x+2. For x=1 and x=2, the moving average is calculated using three and four rows, respectively

I did this.

df['Volume_moving'] = df.iloc[:,5].rolling(window=5).mean()
df

Date    Open    High    Low Close   Volume  Adj Close   Volume_moving
0   2012-10-15  632.35  635.13  623.85  634.76  15446500    631.87  NaN
1   2012-10-16  635.37  650.30  631.00  649.79  19634700    646.84  NaN
2   2012-10-17  648.87  652.79  644.00  644.61  13894200    641.68  NaN
3   2012-10-18  639.59  642.06  630.00  632.64  17022300    629.76  NaN
4   2012-10-19  631.05  631.77  609.62  609.84  26574500    607.07  18514440.0
... ... ... ... ... ... ... ... ...
85  2013-01-08  529.21  531.89  521.25  525.31  16382400    525.31  17504860.0
86  2013-01-09  522.50  525.01  515.99  517.10  14557300    517.10  16412620.0
87  2013-01-10  528.55  528.72  515.52  523.51  21469500    523.51  18185340.0
88  2013-01-11  521.00  525.32  519.02  520.30  12518100    520.30  16443720.0
91  2013-01-14  502.68  507.50  498.51  501.75  26179000    501.75  18221260.0

However, I think that the result is not accurate as I tried it with a different dataframe and get the exact same result.

Can anyone please help me with this?

Try with this:

df['Volume_moving'] = df['Volume'].rolling(window=5).mean()

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