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

使用Pandas apply合并多Excel文件异常:返回Series而非DataFrame

问题解决:合并多个Excel文件为单个DataFrame

你的代码中apply(axis=1)会把每行返回的DataFrame转换成Series的元素,所以最终result_df是一个存储多个小DataFrame的Series,而非合并后的大DataFrame。要得到整合后的DataFrame,只需把这些小DataFrame拼接起来即可,以下是两种可行方案:

方案1:基于现有代码修改

在apply之后用pd.concat()拼接所有返回的DataFrame:

import pandas as pd

def process_row(row):
    liens = row['Liens']
    df_excel = pd.read_excel(liens)
    df_excel['Name'] = row['Name']
    return df_excel

# 先通过apply获取所有小DataFrame的Series,再转成列表后拼接
result_df = pd.concat(new_df.apply(process_row, axis=1).tolist(), ignore_index=True)
  • tolist()把Series转换成存储DataFrame的列表
  • ignore_index=True重置合并后DataFrame的索引,避免索引重复

方案2:更高效的列表推导式(推荐)

相比apply,列表推导式的执行效率更高,直接遍历new_df的行收集DataFrame:

import pandas as pd

dfs = []
for _, row in new_df.iterrows():
    df_excel = pd.read_excel(row['Liens'])
    df_excel['Name'] = row['Name']
    dfs.append(df_excel)

result_df = pd.concat(dfs, ignore_index=True)

额外注意事项

  • 如果存在无法读取的文件,可以在读取时添加异常捕获,避免程序中断:
for _, row in new_df.iterrows():
    try:
        df_excel = pd.read_excel(row['Liens'])
        df_excel['Name'] = row['Name']
        dfs.append(df_excel)
    except Exception as e:
        print(f"读取文件 {row['Liens']} 失败: {str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:31:06