从 excel 文件打印字符串 - 接收错误: 错误中的密钥错误(密钥) 错误: "接口"



我试图复制他在这个视频中所做的事情:https://www.youtube.com/watch?v=vhpTn6JSP9k&t=607s

出于这个原因,我制作了一个名为";testexelfile.xlsx";。

它包含以下内容,没有Excel文件的特殊配置:

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:UserDataXXXOneDrive - XXXDocuments>python blabla.py
Traceback (most recent call last):
File "C:UsersXXXAppDataLocalProgramsPythonPython39libsite-packagespandascoreindexesbase.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libsindex.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libsindex.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libshashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libshashtable_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:UserDataXXXOneDrive - XXXDocumentsblabla.py", line 11, in <module>
xl_value = xldata["Ziel"]["Interface"]
File "C:UsersXXXAppDataLocalProgramsPythonPython39libsite-packagespandascoreseries.py", line 853, in __getitem__
return self._get_value(key)
File "C:UsersXXXAppDataLocalProgramsPythonPython39libsite-packagespandascoreseries.py", line 961, in _get_value
loc = self.index.get_loc(label)
File "C:UsersXXXAppDataLocalProgramsPythonPython39libsite-packagespandascoreindexesbase.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 'Interface'

在我看来,它似乎无法读取Excel文件。根据本文(https://realpython.com/python-keyerror/)它在目录中找不到关键字(我猜是Excel文件(。

在上面提到的文章中,描述了使用.get((关键字来消除KeyError。我不明白的是我将如何在代码中实现这一点。

如果能得到一点帮助就太好了,因为我在编程方面还很在行:(

谢谢你的努力。

请注意,在本教程中,他调用set_index(),以便可以使用代码xldata["ColTitle"]["RowTitle2"]通过列中的文本引用行。但是您传递的是两个不同列的名称!你的意思可能是xl_value = xldata["Ziel"]["G2"]

在上面提到的文章中,描述了用.get()关键字消除KeyError。我不明白的是我将如何在代码中实现这一点。

像这样使用.get()是错误的解决方案。.get()的优点是,如果密钥不存在,您将获得其他对象而不是错误。在这种情况下,这是错误的解决方案,因为您想要使用确实存在的密钥。如果使用.get(),它将防止错误,但输出将不正确。


相反,您需要更改使用的密钥。您可以做的一件有助于了解允许提供哪些密钥的事情是打印出系列的值。示例:

print(xldata["Ziel"])

这将打印出索引(Interface列(和您选择的列(Ziel列(。唯一允许使用的键是索引中的值。

此外,重要的是要知道有两种Pandas对象,Dataframe和Series。它们之间的区别在于数据帧是二维的,序列是一维的。

以下是一个关于如何从Pandas对象中获取数据的好教程:https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

最新更新