简体   繁体   English

计算 pandas 中的移动平均值

[英]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. window 大小为 5,行 x 的移动平均值是根据行 x-2、x-1、x、x+1 和 x+2 计算的。 For x=1 and x=2, the moving average is calculated using three and four rows, respectively对于 x=1 和 x=2,分别使用三行和四行计算移动平均值

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.但是,我认为结果不准确,因为我尝试使用不同的 dataframe 并得到完全相同的结果。

Can anyone please help me with this?谁能帮我解决这个问题?

Try with this:试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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