【发布时间】:2021-05-22 05:05:43
【问题描述】:
我在堆栈溢出中的第一篇文章。
我尝试复制他在此视频中所做的事情: https://www.youtube.com/watch?v=vhpTn6JSP9k&t=607s
出于这个原因,我制作了一个名为“testexelfile.xlsx”的 Excel 文件。
它包含以下内容,没有对Exel文件进行特殊配置:
Model Name Interface Ziel
Model1 Fortigate1 G1 Switch1
Model1 Fortigate1 G2 Switch2
Model1 Fortigate1 G3 Switch3
Model1 Fortigate1 G4 Switch4
Model1 Fortigate1 G5 Switch5
我的代码如下:
import pandas as pd
excel_file = "testexelfile.xlsx"
xldata = pd.read_excel(excel_file, sheet_name= "Sheet1")
#xl_value1 = xldata["Ziel"][2]
#print(xl_value1)
xldata.set_index("Interface",inplace=True)
xl_value = xldata["Ziel"]["Interface"]
print(xl_value)
但我收到以下错误:
C:\UserData\XXX\OneDrive - XXX\Documents>python blabla.py
Traceback (most recent call last):
File "C:\Users\XXX\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Interface'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\UserData\XXX\OneDrive - XXX\Documents\blabla.py", line 11, in <module>
xl_value = xldata["Ziel"]["Interface"]
File "C:\Users\XXX\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py", line 853, in __getitem__
return self._get_value(key)
File "C:\Users\XXX\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py", line 961, in _get_value
loc = self.index.get_loc(label)
File "C:\Users\XXX\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 'Interface'
在我看来,它无法读取 Exel 文件。根据这篇文章 (https://realpython.com/python-keyerror/),它在目录中找不到关键字(我猜是 Excel 文件)。
在提到的文章中,它被描述为使用 .get() 关键字摆脱 KeyError。我不明白我将如何在我的代码中实现这一点。
能得到一点帮助会很高兴,因为我在编程方面仍然很菜鸟:)
感谢您的努力。
【问题讨论】:
标签: python python-3.x pandas