我想在移动时间序列中添加移动平均值计算。

来自Quandl的原始数据

Exchange = Quandl.get("BUNDESBANK/BBEX3_D_SEK_USD_CA_AC_000",
                      authtoken="xxxxxxx")

#               Value
# Date
# 1989-01-02  6.10500
# 1989-01-03  6.07500
# 1989-01-04  6.10750
# 1989-01-05  6.15250
# 1989-01-09  6.25500
# 1989-01-10  6.24250
# 1989-01-11  6.26250
# 1989-01-12  6.23250
# 1989-01-13  6.27750
# 1989-01-16  6.31250

# Calculating Moving Avarage
MovingAverage = pd.rolling_mean(Exchange,5)

#               Value
# Date
# 1989-01-02      NaN
# 1989-01-03      NaN
# 1989-01-04      NaN
# 1989-01-05      NaN
# 1989-01-09  6.13900
# 1989-01-10  6.16650
# 1989-01-11  6.20400
# 1989-01-12  6.22900
# 1989-01-13  6.25400
# 1989-01-16  6.26550

我想在Value之后使用相同的索引(Date)将计算出的移动平均值作为新列添加到右侧。最好我还想将计算的移动平均值重命名为MA

最佳答案

滚动平均值返回一个Series,您只需将其添加为DataFrame(MA)的新列,如下所述。

有关信息,在较新的 Pandas 版本中不建议使用rolling_mean函数。我在示例中使用了新方法,请参见下面的pandas documentation引用。


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

print(df)
#             Value    MA
# Date
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

09-27 05:58