python - Pandas 数据帧 : how to get column mean valuebut taking into account only the rows that have lower index than the one I want to get the mean

标签 python pandas group-by aggregate mean

我遇到的问题是我想预测一支球队对另一支球队的胜利,为此我希望在比赛日期之前获得每场比赛的胜率。

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

所以我想要的是获取本场比赛之前比赛的胜率,知道我的 DataFrame 中有一个列 index 来保持比赛的顺序(即,如果索引匹配的索引低于当前匹配的索引,这意味着之前已经进行过匹配,因此应将本次匹配视为平均值)

请注意,我的专栏是:

indexMatch, nameTeam, isVictoryTeam

(isVictoryTeam= 如果团队 1 获胜,则为 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

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

最佳答案

一定有更好的方法,但这个有效:

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

关于python - Pandas 数据帧 : how to get column mean valuebut taking into account only the rows that have lower index than the one I want to get the mean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037095/

相关文章:

python - 创建具有 02 个日期时间之间差异的列 - Pandas

python - O(log n) 在排序的 python 字典中搜索

python-3.x - 根据 groupby 和 TimeGrouper 之后的列条件从 pandas 数据框中获取行

mysql - 如何查询mysql以选择具有两列非唯一组合的行

python - 使用matplotlib创建雷达图时,有没有办法删除雷达图上的圆圈 'labels'?

python - 从数据框中的列中提取星期几并放入另一列中

python - 我试图在 pandas 中申请 .apply 列,但它抛出 TypeError : 'float' object is not subscriptable

python - 对 Pandas 数据框中的每一行进行排序的最快方法

sql - 尝试使用带有SUM函数的INNER JOIN和GROUP BY SQL,不起作用

mySQL >> 在逗号分隔的字段中查找最常用的词