python-熊猫-按多列分组的移动平均线

对Pandas来说是新手,所以请耐心等待.

我的数据框的格式为

date,name,country,tag,cat,score
2017-05-21,X,US,free,4,0.0573
2017-05-22,X,US,free,4,0.0626
2017-05-23,X,US,free,4,0.0584
2017-05-24,X,US,free,4,0.0563
2017-05-21,X,MX,free,4,0.0537
2017-05-22,X,MX,free,4,0.0640
2017-05-23,X,MX,free,4,0.0648
2017-05-24,X,MX,free,4,0.0668

我正在尝试找到一种在国家/标签/类别组中查找X天移动平均线的方法,因此我需要:

date,name,country,tag,cat,score,moving_average
2017-05-21,X,US,free,4,0.0573,0
2017-05-22,X,US,free,4,0.0626,0.0605
2017-05-23,X,US,free,4,0.0584,0.0594
2017-05-24,X,US,free,4,0.0563,and so on
...
2017-05-21,X,MX,free,4,0.0537,and so on
2017-05-22,X,MX,free,4,0.0640,and so on
2017-05-23,X,MX,free,4,0.0648,and so on
2017-05-24,X,MX,free,4,0.0668,and so on

我尝试根据需要的列对行进行分组,然后使用pd.rolling_mean,但最后得到了一堆NaN

df.groupby(['date', 'name', 'country', 'tag'])['score'].apply(pd.rolling_mean, 2, min_periods=2)  # window size 2

我将如何正确执行此操作?

解决方法:

IIUC:

(df.assign(moving_score=df.groupby(['name','country','tag'], as_index=False)[['score']]
                           .rolling(2, min_periods=2).mean().fillna(0)
                           .reset_index(0, drop=True)))

输出

         date name country   tag  cat   score  moving_score
0  2017-05-21    X      US  free    4  0.0573       0.00000
1  2017-05-22    X      US  free    4  0.0626       0.05995
2  2017-05-23    X      US  free    4  0.0584       0.06050
3  2017-05-24    X      US  free    4  0.0563       0.05735
4  2017-05-21    X      MX  free    4  0.0537       0.00000
5  2017-05-22    X      MX  free    4  0.0640       0.05885
6  2017-05-23    X      MX  free    4  0.0648       0.06440
7  2017-05-24    X      MX  free    4  0.0668       0.06580

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...