足球赛果预测建模新增列时触发IndexError索引越界问题求助
问题根因
触发IndexError的核心原因是你pred函数中a/b/c三个统计对象的初始化、赋值逻辑存在缺陷:
- 你初始将
a/b/c赋值为整数0,第一次执行i==0分支时,若过滤出的curr为空,curr.groupby('Outcome').count()返回的Series没有0/1/2索引,后续访问a[0]/a[1]/a[2]就会触发索引越界 - 循环只处理了
i=0和i=3的分支,i=1/2无任何逻辑,属于无效循环 - 后续胜负判断的逻辑
a[0] > (a[1] and a[2])写法错误,Python中and运算符不会实现「同时大于两个值」的判断逻辑
解决步骤
1. 先修正pred函数的初始化和统计逻辑
import pandas as pd from math import trunc def pred(home,away,score1,score2,data): # 初始化固定索引的Series,默认值为0,避免后续访问索引越界 a = pd.Series([0,0,0], index=[0,1,2]) # Outcome 3种结果:0=Draw 1=Home 2=Away b = pd.Series([0,0], index=[0,1]) # Over 2种结果 c = pd.Series([0,0], index=[0,1]) # btts 2种结果 # 直接处理你需要的两个分支,删除无效循环 # 原i=0分支逻辑 curr = data[(data.POutcome_Home >= trunc(home, 3)) & (data.POutcome_Home < trunc((home+0.001),3)) & (data.POutcome_Away >= trunc(away, 2)) & (data.POutcome_Away < trunc((away+0.01),2)) & (data.PTeam1_Score >= trunc(score1, 2)) & (data.PTeam1_Score < trunc((score1+0.01),2)) & (data.PTeam2_Score >= trunc(score2, 2)) & (data.PTeam2_Score < trunc((score2+0.01),2))] # 用add叠加统计值,不存在的索引自动补0 a = a.add(curr.groupby('Outcome').Outcome.count(), fill_value=0) b = b.add(curr.groupby('Over').Over.count(), fill_value=0) c = c.add(curr.groupby('btts').btts.count(), fill_value=0) # 原i=3分支逻辑 curr = data[(data.POutcome_Home >= trunc(home, 2)) & (data.POutcome_Home < trunc((home+0.01),2)) & (data.POutcome_Away >= trunc(away, 2)) & (data.POutcome_Away < trunc((away+0.01),2)) & (data.PTeam1_Score >= trunc(score1, 2)) & (data.PTeam1_Score < trunc((score1+0.01),2)) & (data.PTeam2_Score >= trunc(score2, 3)) & (data.PTeam2_Score < trunc((score2+0.001),3))] a = a.add(curr.groupby('Outcome').Outcome.count(), fill_value=0) b = b.add(curr.groupby('Over').Over.count(), fill_value=0) c = c.add(curr.groupby('btts').btts.count(), fill_value=0) predict = [] # 修正大小判断逻辑 if a[0] > a[1] and a[0] > a[2]: predict.append("Draw") elif a[1] > a[0] and a[1] > a[2]: predict.append("Home") elif a[2] > a[0] and a[2] > a[1]: predict.append("Away") else: # 增加平局情况的默认处理,避免返回空 predict.append("Unknown") if b[0] > b[1]: predict.append("Under2.5") else: predict.append("Over2.5") if c[0] > c[1]: predict.append("No-BTTS") else: predict.append("BTTS") return predict
2. 额外校验索引一致性
你代码中存在epl_data_main3["Outcome"] = epl_data.apply(...)的赋值操作,请确保epl_data和epl_data_main3的行数、索引完全对齐,避免索引错位导致的越界问题。
内容的提问来源于stack exchange,提问作者osanebi emmanuel
相关产品推荐
相关产品推荐

