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

使用Pandas DataFrame访问'temp'列时触发KeyError问题排查

解决Pandas访问DataFrame列时的KeyError问题

问题出在你的代码上,和Pandas包本身无关。

问题重现

你尝试通过data["temp"]访问Pandas DataFrame的列时抛出KeyError,相关代码如下:

import pandas

data = pandas.read_csv("weather_data.csv")

y = data["temp"]
print(y)

你的CSV文件内容:

day;temp;condition
Monday;12;Sunny
Tuesday ;14;Rain
Wednesday;15;Rain
Tuesday ;14;Cloudy
Friday;21;Sunny
Saturday;22;Sunny
Sunday;24;Sunny

得到的错误信息:

line 3790, in get_loc
    return self._engine.get_loc(casted_key)
  File "index.pyx", line 152, in pandas._libs.index.IndexEngine.get_loc
  File "index.pyx", line 181, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 7080, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 7088, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'temp'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:NAME", line 5, in <module>
    y = data["temp"]
  File "C:\Users\sehab\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\frame.py", line 3893, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\sehab\PycharmProjects\pythonProject\venv\lib\site-packages\pandas\core\indexes\base.py", line 3797, in get_loc
    raise KeyError(key) from err
KeyError: 'temp'

问题原因

你的CSV文件使用**分号(;)作为字段分隔符,但pandas.read_csv()默认使用逗号(,)**作为分隔符。这导致Pandas没有正确解析CSV的列结构,实际上它把整行内容当成了单个列,自然找不到名为temp的列,从而抛出KeyError。

另外CSV里部分行的字段值(比如Tuesday )带有尾部空格,后续访问数据时可能引发匹配问题,建议一并处理。

解决方案

修改read_csv的参数,指定分隔符为分号,同时开启skipinitialspace来忽略字段值前后的空格:

import pandas

# 指定分隔符为分号,并跳过字段值前的空格
data = pandas.read_csv("weather_data.csv", sep=";", skipinitialspace=True)

y = data["temp"]
print(y)

效果验证

运行修正后的代码后,Pandas会正确解析出day、temp、condition三列,data["temp"]可以正常返回温度数据列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:10:19