Python Pandas: Calculate moving average within group
You can use rolling
on groupby
object directly as:
df['moving'] = df.groupby('object').rolling(10)['value'].mean()
The new pandas version throws an error when used direct assign to the column so use:
df['moving'] = df.groupby('object').rolling(10)['value'].mean().reset_index(drop=True)
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.