如何获得熊猫过去几个月的移动平均值

时间:2017-08-22 19:56:49

标签: python pandas datetime

我有一个数据集,第一列是Date,Second列是Price。 日期是交易日。

enter image description here

我想返回一个如下表:

enter image description here

如果日期是从2006年开始的每个月,价格MA是过去N个月的平均价格。(N = [1,2,3,4,5,6])

例如:如果我想在2006年1月1日N = 1 马应该是去年12月的平均价格 如果N = 2 Ma应该是去年11月和12月的平均价格

我已经阅读了一些关于从datetime和groupby提取月份的解决方案。 但是不知道如何把它们放在一起。

3 个答案:

答案 0 :(得分:7)

或者你只是尝试

df.sort_index(ascending=False).rolling(5).mean().sort_index(ascending=True)

有关您的其他问题

index=pd.date_range(start="4th of July 2017",periods=30,freq="D")
df=pd.DataFrame(np.random.randint(0,100,30),index=index)
df['Month']=df.index
df.Month=df.Month.astype(str).str[0:7]
df.groupby('Month')[0].mean()


Out[162]: 
Month
2017-07    47.178571
2017-08    56.000000
Name: 0, dtype: float64

编辑3:对于缺失值滚动两个月的平均值

index=pd.date_range(start="4th of July 2017",periods=300,freq="D")
df=pd.DataFrame(np.random.randint(0,100,300),index=index)
df['Month']=df.index
df.Month=df.Month.astype(str).str[0:7]
df=df.groupby('Month')[0].agg({'sum':'sum','count':'count'})
df['sum'].rolling(2).sum()/df['count'].rolling(2).sum()


Out[200]: 
Month
2017-07          NaN
2017-08    43.932203
2017-09    45.295082
2017-10    46.967213
2017-11    46.327869
2017-12    49.081967
#etc

答案 1 :(得分:3)

将返回使用window参数指定的周期数的滚动平均值。例如。 window = 1将重新恢复原始列表。 Window = 2将计算2天的平均值,依此类推。

index=pd.date_range(start="4th of July 2017",periods=30,freq="D")



df=pd.DataFrame(np.random.randint(0,100,30),index=index)


print([pd.rolling_mean(df,window=i,freq="D") for i in range(1,5)])

.....

2017-07-04   NaN
2017-07-05  20.5
2017-07-06  64.5
2017-07-07  58.5
2017-07-08  13.0
2017-07-09   4.5
2017-07-10  17.5
2017-07-11  23.5
2017-07-12  40.5
2017-07-13  60.0
2017-07-14  73.0
2017-07-15  90.0
2017-07-16  56.5
2017-07-17  55.0
2017-07-18  57.0
2017-07-19  45.0
2017-07-20  77.0
2017-07-21  46.5
2017-07-22   3.5
2017-07-23  48.5
2017-07-24  71.5
2017-07-25  52.0
2017-07-26  56.5
2017-07-27  47.5
2017-07-28  64.0
2017-07-29  82.0
2017-07-30  68.0
2017-07-31  72.5
2017-08-01  58.5
2017-08-02  67.0

.....

此外,您可以使用df dropna方法删除NA值,如:

df.rolling(window=2,freq="D").mean().dropna() #Here you must adjust the window  size

所以整个代码应该打印出几个月的滚动平均值:

print([df.rolling(i,freq="m").mean().dropna() for i in range(len(df.rolling(window=1,freq="m").sum()))])

答案 2 :(得分:-1)

首先,将Date设为索引:

price_df.set_index('Date', inplace=True)
price_df.index = pd.to_datetime(price_df.index)

然后,计算过去N个月的移动平均值:
mv = price_df.rolling(window=i*30, center=False).mean().dropna()

N=i

最后,仅在每个月的第一天返回子集(如果这是您要返回的内容):
mv.ix[mv.index.day==1]

相关问题