New to Pandas, so bear with me.
My dataframe is of the format
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
I'm trying to come up with a way to find the X day moving average within the country/tag/category group, so I need:
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
I tried something on the lines of grouping by the columns I need followed by using pd.rolling_mean but I end up with a bunch of NaN's
df.groupby(['date', 'name', 'country', 'tag'])['score'].apply(pd.rolling_mean, 2, min_periods=2) # window size 2
How would I go about doing this properly?
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)))
Output:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With