Rolling average matching cases across multiple columns

江枫思渺然 提交于 2021-01-29 14:35:40

问题


I'm sorry if this has been asked but I can't find another question like this.

I have a data frame in Pandas like this:

Home   Away   Home_Score   Away_Score
MIL    NYC    1            2
ATL    NYC    1            3
NYC    PHX    2            1
HOU    NYC    1            6

I want to calculate the moving average for each team, but the catch is that I want to do it for all of their games, both home and away combined.

So for a moving average window of size 3 for 'NYC' the answer should be (2+3+2)/3 for row 1 and then (3+2+6)/3 for row 2, etc.


回答1:


You can exploid stack to convert the two columns into one and groupby:

(df[['Home_Score','Away_Score']]
   .stack()
   .groupby(df[['Home','Away']].stack().values)
   .rolling(3).mean()
   .reset_index(level=0, drop=True)
   .unstack()
   .add_prefix('Avg_')
)

Output:

   Avg_Away_Score  Avg_Home_Score
0             NaN             NaN
1             NaN             NaN
2             NaN        2.333333
3        3.666667             NaN


来源:https://stackoverflow.com/questions/60606251/rolling-average-matching-cases-across-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!