Python Pandas: Calculate moving average within group

主宰稳场 提交于 2020-03-18 04:36:06

问题


I have a dataframe containing time series for 100 objects:

object  period  value 
1       1       24
1       2       67
...
1       1000    56
2       1       59
2       2       46
...
2       1000    64
3       1       54
...
100     1       451
100     2       153
...
100     1000    21

I want to calculate moving average with window 10 for the value column. I guess I have to do something like

df.groupby('object').apply(lambda ~calculate MA~) 

and then merge this Series to the original dataframe by object? Can't figure out exact commands


回答1:


You can use rolling with transform:

df['moving'] = df.groupby('object')['value'].transform(lambda x: x.rolling(10, 1).mean())

The 1 in rolling is for minimum number of periods.




回答2:


You can use rolling on groupby object directly as:

df['moving'] = df.groupby('object').rolling(10)['value'].mean()


来源:https://stackoverflow.com/questions/53339021/python-pandas-calculate-moving-average-within-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!