Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: Calculate moving average within group

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

like image 277
Alexandr Kapshuk Avatar asked Nov 16 '18 13:11

Alexandr Kapshuk


People also ask

How do you find average in Groupby pandas?

Pandas Groupby Mean To get the average (or mean) value of in each group, you can directly apply the pandas mean() function to the selected columns from the result of pandas groupby.

How do pandas calculate moving averages?

In Python, we can calculate the moving average using . rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .

How do you find the moving average of a list in Python?

It provides a method called numpy. sum() which returns the sum of elements of the given array. A moving average can be calculated by finding the sum of elements present in the window and dividing it with window size.

How do you find the average of multiple columns in pandas?

Get Column Mean for All Columns To calculate the mean of whole columns in the DataFrame, use pandas. Series. mean() with a list of DataFrame columns. You can also get the mean for all numeric columns using DataFrame.


1 Answers

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.

like image 99
zipa Avatar answered Sep 21 '22 23:09

zipa