如何用Pandas优化球员赛季与单场记录的奖励计算(免双重循环)
优化单场球员奖励计算的Pandas方案
实现步骤
关联单场与赛季球员数据
通过merge按Name字段将单场记录与赛季表中的球员位置关联,彻底避免循环匹配:# 合并获取每场对应的球员位置 merged_data = pd.merge( Game_Wise_Record, Season_Wise_Record[["Name", "Position"]], on="Name", how="left" )加载位置规则字典
将按位置分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)批量计算单场奖励
利用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 )累加奖励至赛季表
按球员分组求和单场奖励,再合并回赛季表更新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
相关产品推荐
相关产品推荐

