如何修复 KeyError - 异常?

How to fix KeyError - exception?

提问人:nina 提问时间:10/31/2023 最后编辑:Hillenina 更新时间:10/31/2023 访问量:52

问:

我不明白为什么钥匙有问题,因为在打印时它存在,有人可以帮忙吗?

% python3 auto_fill_doc_from_excel.py 
['first;last;title']

以下是有关错误的详细信息:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/indexes/base.py", 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: 'first'

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

Traceback (most recent call last):
  File "/Users/ninatyminska/Documents/auto_fill_doc_from_excel.py", line 15, in <module>
    context = {'first_name': row['first'],
                             ~~~^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/series.py", line 1040, in __getitem__
    return self._get_value(key)
           ^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/series.py", line 1156, in _get_value
    loc = self.index.get_loc(label)
          ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pandas/core/indexes/base.py", line 3797, in get_loc
    raise KeyError(key) from err
KeyError: 'first'

除了印刷品,我没有尝试其他任何东西。

代码如下:

from docxtpl import DocxTemplate
from datetime import datetime
import pandas as pd

doc = DocxTemplate("Template_Attendence_Certificate.docx")

today_date = datetime.today().strftime("%d %b, %Y")

my_context = {'today_date': today_date}

df = pd.read_csv('poster_presentation.csv')
#print(df.columns.tolist())

for index, row in df.iterrows():
    context = {'first_name': row['first'],
                      'last_name': row['last'],
               'poster_title': row['title']}
    context.update(my_context)

    doc.render(context)
    doc.save(f"Attendence_Certificate_{index}.docx")
pandas 异常 键错误

评论

0赞 BigBen 10/31/2023
检查尾随空格或大写?
0赞 nina 10/31/2023
感谢您的建议,但似乎该问题与其中任何一个都无关。
0赞 BigBen 10/31/2023
的确切输出是什么?df.columns
0赞 nina 10/31/2023
我不知道如何检查。
0赞 BigBen 10/31/2023
print(df.columns)?

答: 暂无答案