You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取Excel报错排查:新增分组字段后代码失效问题

pd.read_excel读取Excel文件异常问题分析

问题描述

原有Python代码可正常生成包含嵌套数据的Excel文件,但新增Trees Again、UpdatevsNonupdate、responsetimerecodeforACC、Nonupdate、Update分组字段后,执行时在pd.read_excel步骤报错。即使拆分大文件后运行,错误仍存在。

参考代码

import glob
import pandas as pd
import re
import openpyxl

dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name ="Sheet1")
line_numbers = [4, 7]
print("Heey, we read")

dp_max = dp.groupby(['Subject', 'Date & Time', 'Trees Again', 'DifficultyLevel', 'Block', 'UpdatevsNonupdate', 'responsetimerecodeforACC', 'Nonupdate', 'Update'], sort=False).max()
dp_max = dp_max[["Total Training Time"]]
print("This worked. Good start. Yaaaay.s")

dp_max.to_excel('unpredictable_grouped_max_heregoesnothing.xlsx', index=True)
print("This worked. Yaaaay.s")

dp['Signal_Detection2'] = dp.loc[:, 'Signal_Detection']
dp_count = dp.groupby(['Subject', 'Signal_Detection'], sort=False).count()[["Signal_Detection2"]]

dp_count.to_excel('unpredictable_grouped_signal_count_heregoesnothing.xlsx', index=True) 

报错信息

Unexpected exception formatting exception. Falling back to standard exception
Output exceeds the size limit. Open the full output data in a text editor
Traceback (most recent call last):
  File "C:\Users\mxa210135\AppData\Roaming\Python\Python38\site-packages\IPython\core\interactiveshell.py", line 3433, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-9-853a8bf5b14e>", line 5, in <module>
    dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name ="Sheet1")

错误解释与可能原因

  1. 核心错误本质:报错显示pd.read_excel读取文件时触发了未捕获的异常,后续的Unexpected exception formatting exception是IPython处理原始异常时的衍生问题,核心问题出在Excel文件读取环节。
  2. 可能诱因:
    • 文件损坏:新增字段后保存的UnpredictableDataMerge.xlsx可能存在格式损坏,比如单元格格式异常、合并单元格错误、Excel内部结构损坏,拆分文件并未修复损坏问题。
    • 依赖库兼容性:pandas或openpyxl版本存在bug,新增字段的读取逻辑触发了兼容性问题。
    • 数据/字段异常:新增的字段名(如带空格的Trees Again)或对应列的极端数据(超大文本、特殊字符)干扰了解析逻辑。
    • 文件权限/占用:文件被其他程序(如Excel)锁定,或当前用户无读取权限。

排查方向

  • 直接用Excel打开UnpredictableDataMerge.xlsx,检查是否有损坏提示,修复后再尝试读取。
  • 显式指定读取引擎测试:dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name="Sheet1", engine="openpyxl")或尝试engine="xlrd"(注意xlrd对xlsx格式支持有限)。
  • 简化读取逻辑,先读取前10行测试:dp = pd.read_excel("UnpredictableDataMerge.xlsx", sheet_name="Sheet1", nrows=10),排查是否为特定行/列导致的问题。
  • 升级依赖库到稳定版本:pip install --upgrade pandas openpyxl

内容的提问来源于stack exchange,提问作者PythonStudent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:10:43