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))

为什么这段代码不起作用?

我在熊猫中找不到滚动平均属性的错误

4

1 回答 1

3

groupbyrolling,一起使用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
于 2018-10-16T09:28:26.227 回答