我有一个 DataFrame df
,其中每条记录代表一场足球比赛。团队将出现不止一次。我需要为每个团队的分数计算某种滚动平均值(好吧,不完全是字母的滚动平均值)。
date home away score_h score_a
166 2013-09-01 Fulham Chelsea 0 0
167 2013-09-03 Arsenal Everton 0 2
164 2013-09-05 Arsenal Swansea 5 1
165 2013-09-06 Fulham Norwich 0 1
163 2013-09-18 Arsenal Swansea 0 0
我需要计算的是每支球队(主场和客场)的平均得分。
为简洁起见,我们只做主页栏:
grouped = df.groupby('home')
grouped = grouped.sort_index(by='date') # rows inside groups must be in asc order
这导致:
date home away score_h score_a
home
Arsenal 167 2013-09-03 Arsenal Everton 0 2
164 2013-09-05 Arsenal Swansea 5 1
163 2013-09-18 Arsenal Swansea 0 0
Fulham 166 2013-09-01 Fulham Chelsea 0 0
165 2013-09-06 Fulham Norwich 0 1
问题从这里开始
现在,我需要计算团队的“滚动平均值”。让我们为名为 Arsenal
的组手动执行此操作。最后我们应该得到 2 个额外的列,我们称它们为:rmean_h
和 rmean_a
。组中的第一条记录 (167
) 的分数为 0
和 2
。这些的 rmean
分别是 0
和 2
。对于组中的第二条记录 (164
),rmeans 将为 (0+5)/2 = 2.5
和 (2+1)/2 = 1.5
,对于第三条记录,(0+5+0)/3 = 1.66
和 (2+1+0)/3 = 1
。
我们的 DataFrame 现在应该是这样的:
date home away score_h score_a rmean_h rmean_a
home
Arsenal 167 2013-09-03 Arsenal Everton 0 2 0 2
164 2013-09-05 Arsenal Swansea 5 1 2.5 1.5
163 2013-09-18 Arsenal Swansea 0 0 1.66 1
Fulham 166 2013-09-01 Fulham Chelsea 0 0
165 2013-09-06 Fulham Norwich 0 1
我想对我的数据进行这些计算,请问您有什么建议吗?
最佳答案
您可以对每个组应用 expanding_mean
(参见 docs):
grouped = df.sort(columns='date').groupby('home')
grouped['score_h'].apply(pd.expanding_mean)
关于python - 将累积均值函数应用于分组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21092629/