如何基于Win/Lose列修改DataFrame的Points累积计算逻辑?
问题:根据Win/Lose列调整DataFrame的Points计算逻辑
这是此前问题《update a value by running through every row in a data frame with conditions (extension)》的进一步扩展。当前使用的DataFrame新增了Win/Lose列,数据如下:
| Index | A | B | A_yes | B_yes | Win/Lose |
|---|---|---|---|---|---|
| 0 | 2.43 | 1.55 | 1 | 0 | 1 |
| 1 | 2.58 | 1.49 | 0 | 1 | 0 |
| 2 | 1.61 | 2.32 | 1 | 0 | 1 |
| 3 | 2.7 | 1.46 | 1 | 0 | 1 |
其中Win/Lose列中1代表获胜,0代表失败。
目前使用以下代码生成输出:
start = 500 weights = (df["A"].where(df["A_yes"].eq(1), df["B"]) * 0.5 + 0.5).cumprod() df["Points"] = start * weights
生成的输出DataFrame如下:
| Index | A | B | A_yes | B_yes | Points |
|---|---|---|---|---|---|
| 0 | 2.43 | 1.55 | 1 | 0 | 875.5 |
| 1 | 2.58 | 1.49 | 0 | 1 | 1067.5875 |
| 2 | 1.61 | 2.32 | 1 | 0 | 1393.2017 |
| 3 | 2.7 | 1.46 | 1 | 0 | 2557.42324 |
现需修改代码,使其遵循依赖Win/Lose列的计算规则,得到如下期望输出:
| Index | A | B | A_yes | B_yes | Win/Lose | Points |
|---|---|---|---|---|---|---|
| 0 | 2.43 | 1.55 | 1 | 0 | 1 | 857.5 |
| 1 | 2.58 | 1.49 | 0 | 1 | 0 | 428.75 |
| 2 | 1.61 | 2.32 | 1 | 0 | 1 | 707.4375 |
| 3 | 2.7 | 1.46 | 1 | 0 | 1 | 1308.75912 |
解决方案
先拆解计算逻辑:
- 先根据
A_yes/B_yes选择对应的赔率(A或B) - 获胜时(Win/Lose=1):当前Points = 上一轮Points × (0.5×赔率 + 0.5)
- 失败时(Win/Lose=0):当前Points = 上一轮Points × 0.5
可以用向量化写法实现(效率更高),代码如下:
import pandas as pd import numpy as np start = 500 # 选择对应赔率 odds = df["A"].where(df["A_yes"].eq(1), df["B"]) # 根据胜负计算每轮乘数 multipliers = np.where(df["Win/Lose"] == 1, 0.5 * odds + 0.5, 0.5) # 计算累积乘积并乘以初始值 df["Points"] = start * multipliers.cumprod()
验证计算结果:
- 第0行:500 × (0.5×2.43 + 0.5) = 857.5,符合期望
- 第1行:857.5 × 0.5 = 428.75,符合期望
- 第2行:428.75 × (0.5×1.61 + 0.5) = 707.4375,符合期望
- 第3行:707.4375 × (0.5×2.7 + 0.5) ≈ 1308.75912,符合期望
内容的提问来源于stack exchange,提问作者monica
相关产品推荐
相关产品推荐

