合并多Excel工作簿指定工作表为DataFrame时遇错误求助
问题解决:合并含特定名称工作表的Excel文件
错误原因分析
第一个错误TypeError: cannot concatenate object of type '<class 'dict'>'是因为当pd.read_excel的sheet_name参数传入列表时,返回的是字典类型(键为工作表名,值为对应DataFrame),而你直接把字典加入到cefdf列表中,后续pd.concat无法处理字典对象。
第二个错误ValueError: If using all scalar values, you must pass an index是因为你试图把包含DataFrame的字典直接转为DataFrame,这种操作不符合DataFrame的构造逻辑,导致报错。
修正后的代码
方案一:简化版(无需openpyxl)
import pandas as pd import glob pd.set_option("display.max_rows", 100, "display.max_columns", 100) allexcelfiles = glob.glob(r"C:\Users\LELI Laptop 5\Desktop\DTP1\*.xlsx") cefdf = [] for excel_file in allexcelfiles: # 获取当前Excel文件的所有工作表名 xls = pd.ExcelFile(excel_file) # 筛选包含"SAR"的工作表名 sar_sheets = [sheet for sheet in xls.sheet_names if "SAR" in sheet] # 逐个读取符合条件的工作表,加入列表 for sheet in sar_sheets: df = pd.read_excel(excel_file, sheet_name=sheet, nrows=24) cefdf.append(df) # 合并所有DataFrame final_df = pd.concat(cefdf, ignore_index=True)
方案二:保留原思路优化(去掉冗余的openpyxl操作)
如果坚持用openpyxl获取工作表名,也可以简化原代码:
import pandas as pd import glob from openpyxl import load_workbook pd.set_option("display.max_rows", 100, "display.max_columns", 100) allexcelfiles = glob.glob(r"C:\Users\LELI Laptop 5\Desktop\DTP1\*.xlsx") cefdf = [] for excel_file in allexcelfiles: wb = load_workbook(excel_file, read_only=True) # 只读模式提升效率 sar_sheets = [sheet for sheet in wb.sheetnames if "SAR" in sheet] for sheet in sar_sheets: df = pd.read_excel(excel_file, sheet_name=sheet, nrows=24) cefdf.append(df) final_df = pd.concat(cefdf, ignore_index=True)
关键优化点
- 去掉原代码中冗余的
for sheet in wb:循环,直接一次筛选出所有含"SAR"的工作表名 - 遍历筛选后的工作表名列表,逐个读取单个工作表为DataFrame,确保加入
cefdf的都是DataFrame对象,而非字典 - 添加
ignore_index=True参数,避免合并后索引重复
内容的提问来源于stack exchange,提问作者doctor of spin
相关产品推荐
相关产品推荐

