Fareen Walani
Fareen Walani

Reputation: 25

Python - pandas: Rollingmean command is not working

dataframe = pd.DataFrame(data={'user': [1,1,1,1,1,2,2,2,2,2], 'usage': 
[12,18,76,32,43,45,19,42,9,10]})
dataframe['mean'] = dataframe.groupby('user'['usage'].apply(pd.rolling_mean, 2))

Why this code is not working?

i am getting an error of rolling mean attribute is not found in pandas

Upvotes: 0

Views: 162

Answers (1)

jezrael
jezrael

Reputation: 862611

Use groupby with rolling, docs:

dataframe['mean'] = (dataframe.groupby('user')['usage']
                              .rolling(2)
                              .mean()
                              .reset_index(level=0, drop=True))
print (dataframe)
   user  usage  mean
0     1     12   NaN
1     1     18  15.0
2     1     76  47.0
3     1     32  54.0
4     1     43  37.5
5     2     45   NaN
6     2     19  32.0
7     2     42  30.5
8     2      9  25.5
9     2     10   9.5

Upvotes: 3

Related Questions