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

Pandas中列已存在,切片访问却触发KeyError错误

问题现象
  • 用pd.read_excel('data.xlsx')读取Excel得到DataFrame后,打印df.columns能看到'Report #2 Name'、'Report #3 Name'这类列名
  • 但直接用df['Report #2 Name']或df['Report #3 Name']访问会触发KeyError,而'Report #1 Name'等其他列能正常读取
  • 补充测试结果:
    • df.get('Report #2 Name', 'don exist')返回'don exist'
    • df.columns.union(['Report #2 Name'])会新增该列
    • df.columns[12] == 'Report #2 Name'返回False
    • df.columns[12].encode('utf-8')输出b'Report #2\xc2\xa0Name'
原因分析

这些列名里藏了不间断空格(UTF-8编码对应\xc2\xa0),它和普通空格视觉上一模一样,但属于不同字符,导致用普通空格的字符串匹配时完全不生效。

解决办法

方法1:精准匹配列名

直接用包含不间断空格的字符串访问,或者从columns里取对应索引的列名:

# 用转译的不间断空格字符
df['Report #2\xa0Name']
# 或者直接取对应索引的列名
df[df.columns[12]]

方法2:批量清洗列名

把所有列名里的不间断空格替换成普通空格,一劳永逸:

df.columns = df.columns.str.replace('\xa0', ' ')
# 之后就能正常访问了
df['Report #2 Name']

方法3:读取时指定干净列名

如果提前知道所有列名,读取Excel时直接用names参数指定清洗后的列名:

import pandas as pd
# 替换掉列名里的不间断空格,列出所有列
cleaned_cols = ['Report #1 Name', 'Report #2 Name', ...]
df = pd.read_excel('data.xlsx', names=cleaned_cols, header=0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:14:59