Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Pandas - moving average grouped by multiple columns

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...