Python Pandas:计算组内的移动平均值 [英] Python Pandas: Calculate moving average within group
本文介绍了Python Pandas:计算组内的移动平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据帧,其中包含100个对象的时间序列:
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
我想在窗口10中为value
列计算移动平均线.我想我必须做类似的事情
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
推荐答案
You can use rolling with transform
:
df['moving'] = df.groupby('object')['value'].transform(lambda x: x.rolling(10, 1).mean())
rolling
中的1
用于最小周期数.
The 1
in rolling
is for minimum number of periods.
这篇关于Python Pandas:计算组内的移动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文