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

Pandas中TypeError与InvalidIndexError问题排查求助

问题与修复:世界杯模拟Pandas代码的索引错误

问题现象

运行世界杯模拟代码时触发TypeError和InvalidIndexError,报错指向使用info.at为top16、top8等列表批量赋值的语句,提示列表是无效索引。移除columns=cols后代码可运行但结果为空。

报错原因

pandas.DataFrame.at是标量索引器,仅支持单个行索引和单个列名的标量输入,无法处理列表类型的批量索引。而代码中top16、top8等都是包含多个球队名称的列表,用at操作就会触发索引错误。移除columns=cols后结果为空,是因为DataFrame失去了预设的列结构,后续赋值无法对应到正确的字段。

修复方案

将批量赋值的at替换为loc,loc支持列表作为行/列索引,可实现批量赋值操作。同时保留columns=cols确保DataFrame的列结构正确,避免结果为空。

修改后的完整代码

def SimulaCopa(dados):
    cols = ['1st', '2nd', '3rd', '4th', 'Oitavas', 'Quartas', 'Semis', 'Final', 'Campeão']
    n = dados.shape[0]
    m = len(cols)
    aux = np.array(np.zeros(n*m).reshape(n, m))
    info = pd.DataFrame(aux, columns=cols, index=dados.index)
    info = info.astype(int)
      
    top16 = []  
    for i in list('ABCDEFGH'):
        a = JogosGrupo(dados, i)[0] 
        top16 += a.index[:2].tolist()
        anomes = a.index.to_list() 
        # 单个标量索引仍可使用at
        info.at[anomes[0], '1st'] = 1
        info.at[anomes[1], '2nd'] = 1
        info.at[anomes[2], '3rd'] = 1
        info.at[anomes[3], '4th'] = 1
    

    qf1 = JogoMataMata(top16[0], top16[3])   #A1 x B2
    qf2 = JogoMataMata(top16[2], top16[1])   #B1 x A2
    qf3 = JogoMataMata(top16[4], top16[7])   #C1 x D2 
    qf4 = JogoMataMata(top16[6], top16[5])   #D1 x C2
    qf5 = JogoMataMata(top16[8], top16[11])  #E1 x F2
    qf6 = JogoMataMata(top16[10], top16[9])  #F1 x E2
    qf7 = JogoMataMata(top16[12], top16[15]) #G1 x H2
    qf8 = JogoMataMata(top16[14], top16[13]) #H1 x G2

    top8 = [qf1, qf2, qf3, qf4, qf5, qf6, qf7, qf8]
    

    sf1 = JogoMataMata(qf1, qf3)
    sf2 = JogoMataMata(qf2, qf4) 
    sf3 = JogoMataMata(qf5, qf7) 
    sf4 = JogoMataMata(qf6, qf8) 

    top4 = [sf1, sf2, sf3, sf4]

    f1 = JogoMataMata(sf1, sf3) 
    f2 = JogoMataMata(sf2, sf4) 
    top2 = [f1, f2]

    top1 = JogoMataMata(f1, f2)

    # 批量赋值替换为loc
    info.loc[top16, 'Oitavas'] = 1
    info.loc[top8, 'Quartas'] = 1
    info.loc[top4, 'Semis'] = 1
    info.loc[top2, 'Final'] = 1
    info.at[top1, 'Campeão'] = 1  # top1是单个值,仍用at没问题
   

    return info

额外说明

  • 单个标量索引的场景(如anomes[0]、top1)仍可保留at,它比loc在标量操作上更高效。
  • 需确保JogoMataMata函数返回的是与dados.index匹配的球队名称字符串,否则loc仍会触发索引不存在的错误。

内容的提问来源于stack exchange,提问作者Lucas Mendes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:55:28