提问人:Sehaba Aymene 提问时间:11/14/2023 最后编辑:Sehaba Aymene 更新时间:11/14/2023 访问量:74
使用 pandas 数据帧时出现关键错误 [重复]
Key error when working with pandas dataframe [duplicate]
问:
尝试以这种方式访问 pandas 数据帧中的单个或多个元素时出现错误 data[“temp”]。以下是有关如何加载数据的代码片段:
import pandas
data = pandas.read_csv("weather_data.csv")
y = data["temp"]
print(y)
csv 文件 -> :
日;临时;条件 星期一;12;晴朗 星期二;14;雨 星期三;15;雨 星期二;14;多云 星期五;21;晴朗 星期六;12 倍晴朗 星期日;24;晴朗
这是我收到的错误:
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'
是我的代码有问题还是 pandas 的包有问题?
答:
0赞
alec_djinn
11/14/2023
#1
您没有正确解析 csv,因为默认分隔符是,但您有。","
";"
请尝试以下操作:
data = pandas.read_csv(
filepath_or_buffer="weather_data.csv",
sep=";",
header=0
)
评论
1赞
alec_djinn
11/14/2023
@BigBen好点!现在投票...
评论
data.columns
'temp'
data = pandas.read_csv("weather_data.csv", sep=";")