pd.concat合并DataFrame报错ValueError: No objects to concatenate求助
解决pd.concat触发ValueError: No objects to concatenate的问题
问题场景
通过pandas、xlwings读取指定目录下所有.xlsx文件,提取第一个工作表中名为Table1的表格数据,用映射表重命名列名,添加源文件名后存入列表,最终合并时触发错误。
代码
import pandas as pd from pathlib import Path import xlwings as xw INPUT_DIR = Path(__file__).parent / "both" files = list(INPUT_DIR.glob("*.xlsx")) mapping_table = {"SROCode": "srocode", "InternalDocumentNumber": "internaldocumentnumber", "DocNo": "docno", "DocName": "docname", "RegistrationDate": "registrationdate", "SROName": "sroname", "SellerParty": "sellerparty", "PurchaserParty": "purchaserparty", "PropertyDescription": "propertydescription", "AreaName": "areaname"} dataframes = [] with xw.App(visible=False) as app: for file in files: wb = app.books.open(file) sht = wb.sheets[0] df = sht.tables["Table1"].range.options(pd.DataFrame, index=False).value df = df.rename(columns=mapping_table) df["Source Name"] = file.stem dataframes.append(df) wb.close() combined_df = pd.concat(dataframes) wb_combined = app.books.add() wb_combined.sheets[0].range("A1").options(pd.DataFrame, index=False).value = combined_df wb.save(Path(__file__).parent / "Combined_Data.xlsx") wb_combined.close()
报错信息(中文翻译)
/Users/abhijitchavan/venv/bin/python /Users/abhijitchavan/PycharmProjects/FILE CONVERT/main.py 回溯(最近的调用最后): 文件 "/Users/abhijitchavan/PycharmProjects/FILE CONVERT/main.py",第23行,在 <module> 中 combined_df = pd.concat(dataframes) 文件 "/Users/abhijitchavan/venv/lib/python3.9/site-packages/pandas/util/_decorators.py",第317行,在 wrapper 中 return func(*args, **kwargs) 文件 "/Users/abhijitchavan/venv/lib/python3.9/site-packages/pandas/core/reshape/concat.py",第369行,在 concat 中 op = _Concatenator( 文件 "/Users/abhijitchavan/venv/lib/python3.9/site-packages/pandas/core/reshape/concat.py",第426行,在 __init__ 中 raise ValueError("No objects to concatenate") ValueError: 没有可合并的对象
错误原因
这个错误说明dataframes列表是空的,没有任何DataFrame被成功添加进去,可能的原因包括:
- 指定的
both目录下没有找到任何.xlsx文件 - 找到的文件中,第一个工作表不存在名为
Table1的表格,导致代码抛出异常后终止循环 - 读取的
Table1表格本身没有数据,或者处理过程中出现未捕获的异常
修复步骤
1. 验证文件是否存在
在循环前添加打印代码,确认是否读取到目标文件:
print(f"找到的xlsx文件数量: {len(files)}") print("文件列表:", files)
如果输出数量为0,检查both目录的位置是否正确(是否和脚本在同一目录下),以及目录内是否有.xlsx文件。
2. 添加异常处理与校验逻辑
修改循环部分,增加表格存在性检查、数据空值检查,以及异常捕获,避免单个文件出错导致整个流程中断:
for file in files: try: wb = app.books.open(file) sht = wb.sheets[0] # 检查当前工作表是否存在Table1表格 table_names = [tbl.name for tbl in sht.tables] if "Table1" not in table_names: print(f"警告:文件 {file.name} 的第一个工作表中没有找到Table1表格,跳过该文件") wb.close() continue df = sht.tables["Table1"].range.options(pd.DataFrame, index=False).value # 检查读取的DataFrame是否为空 if df.empty: print(f"警告:文件 {file.name} 的Table1表格无数据,跳过该文件") wb.close() continue # 重命名列并添加源文件名 df = df.rename(columns=mapping_table) df["Source Name"] = file.stem dataframes.append(df) print(f"成功处理文件: {file.name}") wb.close() except Exception as e: print(f"处理文件 {file.name} 时出错: {str(e)}") # 确保出错时关闭文件 if 'wb' in locals(): wb.close()
3. 修复保存文件的bug
原代码最后保存时用了wb.save(),但此时wb是循环中最后一个打开的文件,应该改为保存新建的合并文件wb_combined:
wb_combined.save(Path(__file__).parent / "Combined_Data.xlsx")
4. 合并前检查列表是否为空
在执行pd.concat前添加判断,避免再次触发错误:
if not dataframes: print("没有可合并的有效数据,终止流程") else: combined_df = pd.concat(dataframes) # 后续保存逻辑...
内容的提问来源于stack exchange,提问作者abhijit chavan
相关产品推荐
相关产品推荐

