Pandas DataFrame:如何获取列均值,但仅考虑索引比我要获取均值低的行

时间:2018-08-27 10:15:21

标签: python pandas group-by aggregate mean

我的问题是我想预测一支球队对另一支球队的胜利,我想要做到的是每场比赛在比赛日期之前每支球队的胜率。

但是使用df.groupBy("teamName").agg({"isVictory":"mean"})可以为我提供一支无法使用的全局团队力量,因为您不应该知道此时此刻所有比赛的胜率。

所以我想得到的是这场比赛之前的比赛获胜率,因为我知道我的DataFrame中有一列index保持比赛的顺序(即,如果比赛的索引低于当前匹配项的索引,则表明该匹配项已在之前进行过,因此应在均值中考虑该匹配项)

请注意,我的专栏是:

  

indexMatch,nameTeam,isVictoryTeam

(isVictoryTeam =如果Team1获胜,则为0,如果Team失败则为0)

数据集示例:

   IndexMatch  isVictoryTeam team   winrate
0           1              1    a       NaN
1           2              0    a         1
2           3              1    a       0.5
3           4              1    a    0.6667

赢率是预期的输出。
预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

必须有一种更好的方法,但这是可行的:

df = pd.DataFrame({'team': [' a', ' a', ' a', ' a', 'b', 'b', 'c'],
                   'IndexMatch': [1, 2, 3, 4, 5, 6, 7],
                   'isVictoryTeam': [1, 0, 1, 1, 0, 1, 1]})
df['winrate'] = df.groupby('team')['isVictoryTeam'].expanding().mean().reset_index().groupby('team')['isVictoryTeam'].shift().reset_index(drop=True)
df
#   IndexMatch  isVictoryTeam team   winrate
#0           1              1    a       NaN
#1           2              0    a  1.000000
#2           3              1    a  0.500000
#3           4              1    a  0.666667
#4           5              0    b       NaN
#5           6              1    b  0.000000
#6           7              1    c       NaN