0
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

cs95
  • 379,657
  • 97
  • 704
  • 746
  • what's the definition of pd variable? it probably does not have method rolling_mean defined – DonPaulie Oct 16 '18 at 09:32
  • You have a syntax error (missing parenthesis) in your code. Can you please fix it first, and include the error message? – IanS Oct 16 '18 at 09:34

1 Answers1

3

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252