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

如何解决Pandas DataFrame按标签访问行时的KeyError问题?

问题排查与解决

问题根源

从你的输出可以看到,DataFrame的索引值实际包含单引号(比如显示的'Fp1',实际存储的字符串是'Fp1'而非Fp1),但你用df.loc['Fp1']查找的是不含引号的字符串,两者不匹配,因此抛出KeyError。

解决方法

以下三种方法任选其一即可:

方法1:读取文件时直接清理索引

在pd.read_excel中使用converters参数,处理索引列去掉单引号:

df = pd.read_excel('./eeg_samples/chanlocs67.xlsx', usecols=[0,3,4,5], index_col='labels',
                   converters={'labels': lambda x: x.strip("'")})
df.index.names = [None]
print(df.loc['Fp1'])

方法2:使用带引号的索引值查找

直接匹配实际存储的索引字符串(包含单引号):

print(df.loc["'Fp1'"])

方法3:读取后批量清理索引

如果已经完成文件读取,可事后处理索引去掉引号:

df.index = df.index.str.strip("'")
print(df.loc['Fp1'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 05:50:26