D:\python\program\Lib\site-packages\flask_admin\contrib\__init__.py:2: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. __import__('pkg_resources').declare_namespace(__name__) Traceback (most recent call last): File "D:\python\program\Lib\site-packages\pandas\core\indexes\base.py", line 3805, in get_loc return self._engine.get_loc(casted_key) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "index.pyx", line 167, in pandas._libs.index.IndexEngine.get_loc File "index.pyx", line 196, in pandas._libs.index.IndexEngine.get_loc File "pandas\\_libs\\hashtable_class_helper.pxi", line 7081, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas\\_libs\\hashtable_class_helper.pxi", line 7089, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: '邮编' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "d:\xw\22300434王渝钦结课项目1\app.py", line 97, in <module> initialize_data() File "d:\xw\22300434王渝钦结课项目1\app.py", line 36, in initialize_data import_data() File "d:\xw\22300434王渝钦结课项目1\app.py", line 53, in import_data postal_code=row['邮编'], ~~~^^^^^^^^ File "D:\python\program\Lib\site-packages\pandas\core\series.py", line 1121, in __getitem__ return self._get_value(key) ^^^^^^^^^^^^^^^^^^^^ File "D:\python\program\Lib\site-packages\pandas\core\series.py", line 1237, in _get_value loc = self.index.get_loc(label) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\program\Lib\site-packages\pandas\core\indexes\base.py", line 3812, in get_loc raise KeyError(key) from err KeyError: '邮编'
时间: 2025-06-30 18:16:12 浏览: 10
你遇到的错误是:
```
KeyError: '邮编'
```
这个错误发生在使用 `pandas` 读取 Excel 文件时,程序尝试访问列名 `'邮编'`,但该列并不存在于数据中。
---
## ✅ 错误原因分析
| 原因 | 描述 |
|------|------|
| ❌ Excel 表头不匹配 | Excel 文件中的列名不是“邮编”,可能是其他名称如“邮政编码”、“邮编:”或有空格等问题。 |
| ❌ 列名大小写/空格问题 | 比如表头是 `"邮编 "`(后面带空格)或者 `"邮编:"`(带冒号)。 |
| ❌ pandas 读取方式未正确识别表头 | 如果第一行不是标题,而是数据,则会导致列名混乱。 |
---
## ✅ 解决方案
我们提供一个**健壮的数据导入函数**,能够自动检测列名、处理异常情况,并避免 KeyError。
### ✅ 示例代码:从 Excel 导入学校信息,兼容多种列名格式
```python
import pandas as pd
from app import db, School # 假设你已经定义好了 Flask-SQLAlchemy 的 db 和 School 模型
def import_schools_from_excel(file_path, city_id):
# 读取 Excel 文件
df = pd.read_excel(file_path)
# 打印列名用于调试
print("Excel 列名:", df.columns.tolist())
# 定义列名映射关系(支持多个可能的列名)
column_mapping = {
'name': ['中学名称', '学校名称', 'school_name'],
'district': ['所在城区', '区域', 'district'],
'postal_code': ['邮编', '邮政编码', 'zip_code', 'postcode'],
'description': ['简介', 'description', '备注']
}
# 辅助函数:查找最接近的列名
def find_column(df_cols, possible_names):
for name in possible_names:
if name in df_cols:
return name
return None
# 动态获取列名
name_col = find_column(df.columns, column_mapping['name'])
district_col = find_column(df.columns, column_mapping['district'])
postal_code_col = find_column(df.columns, column_mapping['postal_code'])
description_col = find_column(df.columns, column_mapping['description'])
# 遍历每一行插入数据库
for index, row in df.iterrows():
school = School(
name=str(row[name_col]).strip() if name_col and pd.notna(row[name_col]) else '',
district=str(row[district_col]).strip() if district_col and pd.notna(row[district_col]) else '',
postal_code=str(row[postal_code_col]).strip() if postal_code_col and pd.notna(row[postal_code_col]) else '',
description=str(row[description_col]).strip() if description_col and pd.notna(row[description_col]) else '',
city_id=city_id
)
db.session.add(school)
db.session.commit()
print("数据导入完成")
```
---
## ✅ 使用说明
你可以这样调用它:
```python
import_schools_from_excel('schools.xlsx', city_id=1)
```
其中:
- `schools.xlsx` 是你的 Excel 文件;
- `city_id` 是外键字段,你需要根据实际情况填写或动态获取。
---
## ✅ 代码解释
| 特性 | 说明 |
|------|------|
| `find_column()` | 查找最合适的列名,支持多个别名,比如“邮编”、“邮政编码”都能被识别 |
| `pd.notna()` | 防止空值导致转换失败 |
| `.strip()` | 清除字符串前后多余的空白字符 |
| `print("Excel 列名:", ...)` | 调试信息,帮助确认列名是否正确 |
---
## ✅ 如何验证列名是否正确?
你可以单独运行以下代码来查看 Excel 文件的结构:
```python
df = pd.read_excel('schools.xlsx')
print(df.head())
print("列名:", df.columns.tolist())
```
输出示例:
```
中学名称 所在城区 邮编 简介
0 北京一中 朝阳区 100084 这是一所重点中学
1 上海二中 黄浦区 200001 创建于1905年
列名: ['中学名称', '所在城区', '邮编', '简介']
```
如果列名显示为中文,那就可以确定应使用 `'邮编'`。
---
##
阅读全文
相关推荐



















