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

Pandas通过列名和索引访问单元格触发KeyError('playerName')求助

问题分析与解决

错误核心原因

你的代码问题出在遍历对象错误:

  • for i in fileIn 遍历的是DataFrame的列名(即'playerName'、'survivability'),而非行索引。
  • 当你执行fileIn['playerName'][i]时,i是字符串列名,Pandas会尝试查找索引为该字符串的行,自然不存在,触发KeyError。
  • 同时players[i]也会报错,因为列表仅支持数字索引访问,无法用字符串定位。
  • 额外隐患:你的Player类定义的是类属性,所有实例会共享同一个name值,应该改为实例属性保证独立性。

修正后的代码

import pandas

players = []

class Player:
    def __init__(self):
        # 定义实例属性,每个Player实例独立持有
        self.name = ""
        self.survivability = 0

fileIn = pandas.read_csv('C:/Users/<me>/Downloads/input.csv')

# 使用iterrows()遍历每一行,index为行索引,row为该行的Series数据
for index, row in fileIn.iterrows():
    new_player = Player()
    # 通过列名直接从row中提取对应值
    new_player.name = str(row['playerName'])
    new_player.survivability = row['survivability']
    players.append(new_player)
    print(f"Player {index + 1}'s profile is complete.")

可选遍历方式(数字索引版)

如果你习惯用数字索引遍历,也可以用loc直接定位单元格:

for i in range(len(fileIn)):
    new_player = Player()
    new_player.name = str(fileIn.loc[i, 'playerName'])
    new_player.survivability = fileIn.loc[i, 'survivability']
    players.append(new_player)
    print(f"Player {i + 1}'s profile is complete.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:12:34