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

调用DataFrame中'Not polished'列时持续出现KeyError问题求助

解决DataFrame读取Not polished列的KeyError问题

我在操作Pandas DataFrame时,读取名为Not polished的列始终触发KeyError,哪怕修改了原始数据集的列名,所有针对该列的操作都会报错。报错详情如下:

KeyError
Traceback (most recent call last)
File C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py:3621, in Index.get_loc(self, key, method, tolerance)
   3620 try:
-> 3621     return self._engine.get_loc(casted_key)
   3622 except KeyError as err:

File C:\ProgramData\Anaconda3\lib\site-packages\pandas\_libs\index.pyx:136, in pandas._libs.index.IndexEngine.get_loc()

File C:\ProgramData\Anaconda3\lib\site-packages\pandas\_libs\index.pyx:163, in pandas._libs.index.IndexEngine.get_loc()

File pandas\_libs\hashtable_class_helper.pxi:5198, in pandas._libs.hashtable.PyObjectHashTable.get_item()

File pandas\_libs\hashtable_class_helper.pxi:5206, in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Not polished'

实用解决步骤

  • 排查列名隐藏字符:很多时候列名前后有空格、制表符或不可见Unicode字符,肉眼无法区分。执行以下代码确认真实列名:
    print(df.columns.tolist())
    # 或者筛选包含关键词的列
    print([col for col in df.columns if 'polished' in col])
    
    直接复制输出的列名用于访问,避免手动输入的误差。
  • 读取数据时手动指定列名:如果是从文件(如CSV)读取数据,直接在读取阶段指定列名,覆盖原始列名:
    import pandas as pd
    df = pd.read_csv('your_data.csv', names=['列1', 'Not polished', '列3', ...], header=0)
    
  • 批量清理列名格式:统一处理所有列名,去除前后空格、替换多余空白字符:
    df.columns = df.columns.str.strip().str.replace(r'\s+', ' ', regex=True)
    
  • 验证数据读取完整性:用df.head()查看前几行数据,确认Not polished列确实存在且列名正确。
  • 重置列索引:如果列索引存在异常,执行以下代码重置后再尝试访问:
    df.reset_index(drop=True, inplace=True)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:10:49