You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas优化球员赛季与单场记录的奖励计算(免双重循环)

优化单场球员奖励计算的Pandas方案

实现步骤

  1. 关联单场与赛季球员数据
    通过merge按Name字段将单场记录与赛季表中的球员位置关联,彻底避免循环匹配:

    # 合并获取每场对应的球员位置
    merged_data = pd.merge(
        Game_Wise_Record,
        Season_Wise_Record[["Name", "Position"]],
        on="Name",
        how="left"
    )
    
  2. 加载位置规则字典
    将按位置分Sheet的规则表转为字典,便于快速调用对应位置的奖励规则:

    # 读取所有位置规则并存储为字典(Sheet名对应位置名称)
    rule_book = {}
    xls = pd.ExcelFile("Player Goals File.xlsx")
    for pos in xls.sheet_names:
        rule_book[pos] = pd.read_excel(xls, sheet_name=pos)
    
  3. 批量计算单场奖励
    利用apply逐行调用自定义函数,传入单场数据与对应位置的规则表:

    def compute_game_reward(row, rules):
        pos = row["Position"]
        return calculatePointsGame(row, rules.get(pos, pd.DataFrame()))
    
    # 生成每场奖励列
    merged_data["Game_Reward"] = merged_data.apply(
        compute_game_reward,
        axis=1,
        rules=rule_book
    )
    
  4. 累加奖励至赛季表
    按球员分组求和单场奖励,再合并回赛季表更新Reward列:

    # 按球员汇总单场总奖励
    player_total = merged_data.groupby("Name")["Game_Reward"].sum().reset_index()
    
    # 合并到赛季表并累加奖励
    Season_Wise_Record = Season_Wise_Record.merge(player_total, on="Name", how="left")
    Season_Wise_Record["Reward"] += Season_Wise_Record["Game_Reward"].fillna(0)
    Season_Wise_Record.drop("Game_Reward", axis=1, inplace=True)
    

额外优化提示

  • 若calculatePointsGame的逻辑可拆解,优先用Pandas向量化操作(如np.select、条件列计算)替代apply,能进一步提升计算效率。
  • 若存在重名球员,可增加Team等字段作为merge的联合键,避免匹配错误。

内容的提问来源于stack exchange,提问作者Asad Hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:26:05