我具有以下示例数据框:-
daterange total_val
02/01/00 20.0005679
09/01/00 20.0005679
16/01/00 20.0005679
23/01/00 20.0005679
30/01/00 20.0005679
06/02/00 42.50061196
13/02/00 42.50061196
20/02/00 42.50061196
27/02/00 42.50061196
05/03/00 85.00073436
12/03/00 85.00073436
19/03/00 85.00073436
26/03/00 85.00073436
02/04/00 95.00083227
09/04/00 95.00083227
16/04/00 95.00083227
我需要分别计算3个月,6个月的移动平均值。
当前,我在将数据从每月移至每周之前使用了以下代码,但这使ma可以保持一个月的一致性:-
df['total_val_ma3'] = df['total_val'].shift(1).rolling(3).mean()
df['total_val_ma6'] = df['total_val'].shift(1).rolling(6).mean()
df = func_resample_from_monthly(df, 'daterange', 'Weekly')
def func_resample_from_monthly(df,col, category):
df.set_index(col, inplace=True)
df.index = pd.to_datetime(df.index, dayfirst=True)
#add new next month for correct resample
idx = df.index[-1] + pd.offsets.MonthBegin(1)
df = df.append(df.iloc[[-1]].rename({df.index[-1]: idx}))
if category == "Daily":
df = df.resample('D').ffill().iloc[:-1]
elif category == "Weekly":
df = df.resample('W').ffill().iloc[:-1]
df.reset_index(inplace=True)
return df
是否有任何建议可以用熊猫的每周数据来平均移动3个月,6个月,或者我使用的方法也合适?