【问题标题】:How to find the rolling percentage Pandas如何找到熊猫的滚动百分比
【发布时间】:2021-09-02 11:39:18
【问题描述】:
我想通过滚动计数来了解一匹马的胜率。
这就是我目前所拥有的
| Horse |
Another header |
Wins |
| A |
1 |
1 |
| A |
2 |
1 |
| A |
1 |
2 |
| B |
3 |
0 |
| B |
1 |
1 |
| B |
3 |
1 |
这就是我想要的。
| Horse |
Another header |
Wins |
Win Perc |
| A |
1 |
1 |
100% |
| A |
2 |
1 |
50% |
| A |
1 |
2 |
66% |
| B |
3 |
0 |
0% |
| B |
1 |
1 |
50% |
| B |
3 |
1 |
33% |
如果可能,最好知道过去 3 场比赛的总胜率和胜率??
【问题讨论】:
标签:
python
pandas
statistics
percentage
rolling-computation
【解决方案1】:
你可以这样做:
>>> import pandas as pd
>>> df = pd.DataFrame({"horse": ["A", "A", "A", "B", "B", "B"], "wins": [1, 1, 2, 0, 1, 1]})
>>> df
horse wins
0 A 1
1 A 1
2 A 2
3 B 0
4 B 1
5 B 1
>>> df["win_pct"] = df["wins"] / (df.groupby("horse").cumcount() + 1) * 100
>>> df
horse wins win_pct
0 A 1 100.000000
1 A 1 50.000000
2 A 2 66.666667
3 B 0 0.000000
4 B 1 50.000000
5 B 1 33.333333