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

如何用Python Pandas将多文件分析结果追加至同一Excel工作表

问题描述

我是Python新手,写代码时碰到不少问题。我把CSV转成Excel文件后,从每个文件里生成了一组分析结果(比如文件1输出U1、V1、W1、X1,文件2输出U2、V2、W2、X2这类)。我想把这些结果导出到同一个Excel文件的多行里,而不是只保留单个文件的结果。我创建了DataFrame并用to_excel方法导出,但最终Excel里只有最后一个文件的分析数据。另外,我还需要在最终的Excel表中加上对应的Excel文件名信息。

以下是我导出结果的Python代码片段:

for excel_file in glob(r"C:\Users\sujith0327\pythonProject2\0 Nano Attempts*.xlsx"):
    df_excel = pd.read_excel(excel_file)

    max_depth_no = df_excel['Depth(nm)'].idxmax()

    loading_part = df_excel.iloc[0:max_depth_no]
    unloading_part = df_excel.iloc[max_depth_no:-1]

    y = np.array(loading_part['Load (µN)'])
    area_load = trapz(y, dx=0.01)

    y = np.array(unloading_part['Load (µN)'])
    area_unload = trapz(y, dx=0.01)

    y = np.array(df_excel['Load (µN)'])
    area = trapz(y, dx=0.01)

    reversible_area = area_load - area_unload
    irreversible_area = area_unload
    total_area = reversible_area + irreversible_area

    reversible_share = (reversible_area / total_area) * 100
    irriversible_share = (irreversible_area / total_area) * 100

    max_depth = df_excel['Depth(nm)'][max_depth_no]
    remnant_depth = df_excel['Depth(nm)'].iat[-1]
    max_load = df_excel['Load (µN)'][max_depth_no]
    depth_recoverability = (1 - (remnant_depth / max_depth)) * 100

    print(max_depth, remnant_depth, max_load, depth_recoverability, reversible_share, irriversible_share)

    data = {'Max Load ((µN)': [max_load], 'Max Depth (nm)': [max_depth], 'Remnant Depth(nm)': [remnant_depth],
            'Depth Recoverability (%)': [depth_recoverability], 'Reversible Energy (%)': [reversible_share],
            'Irriversible Energy (%)': [irriversible_share]}
    frame = pd.DataFrame(data)
    print(data)

frame.to_excel("00 ALL RESULTS.xlsx")
解决方案

问题根源

你的代码在循环里每次都会重新赋值frame,覆盖掉之前文件的结果,所以最终导出的只有最后一个文件的数据。同时代码里没有把文件名加入结果中。

修改后的完整代码

import pandas as pd
import numpy as np
from scipy.integrate import trapz
import glob

# 初始化空列表,用来存储每个文件的结果DataFrame
all_results = []

for excel_file in glob(r"C:\Users\sujith0327\pythonProject2\0 Nano Attempts*.xlsx"):
    df_excel = pd.read_excel(excel_file)

    max_depth_no = df_excel['Depth(nm)'].idxmax()

    loading_part = df_excel.iloc[0:max_depth_no]
    unloading_part = df_excel.iloc[max_depth_no:-1]

    y = np.array(loading_part['Load (µN)'])
    area_load = trapz(y, dx=0.01)

    y = np.array(unloading_part['Load (µN)'])
    area_unload = trapz(y, dx=0.01)

    y = np.array(df_excel['Load (µN)'])
    area = trapz(y, dx=0.01)

    reversible_area = area_load - area_unload
    irreversible_area = area_unload
    total_area = reversible_area + irreversible_area

    reversible_share = (reversible_area / total_area) * 100
    irriversible_share = (irreversible_area / total_area) * 100

    max_depth = df_excel['Depth(nm)'][max_depth_no]
    remnant_depth = df_excel['Depth(nm)'].iat[-1]
    max_load = df_excel['Load (µN)'][max_depth_no]
    depth_recoverability = (1 - (remnant_depth / max_depth)) * 100

    print(max_depth, remnant_depth, max_load, depth_recoverability, reversible_share, irriversible_share)

    # 提取文件名(如果需要完整路径可直接用excel_file)
    filename = pd.io.common.path.basename(excel_file)
    
    # 新增文件名字段
    data = {'文件名': [filename],
            'Max Load ((µN)': [max_load], 
            'Max Depth (nm)': [max_depth], 
            'Remnant Depth(nm)': [remnant_depth],
            'Depth Recoverability (%)': [depth_recoverability], 
            'Reversible Energy (%)': [reversible_share],
            'Irriversible Energy (%)': [irriversible_share]}
    frame = pd.DataFrame(data)
    # 将当前文件的结果添加到列表中
    all_results.append(frame)
    print(data)

# 合并所有结果为一个DataFrame,重置索引
final_frame = pd.concat(all_results, ignore_index=True)
# 导出到Excel,不生成索引列
final_frame.to_excel("00 ALL RESULTS.xlsx", index=False)

关键改动说明

  • 收集所有结果:用all_results列表存储每个文件生成的小DataFrame,避免循环中覆盖数据
  • 添加文件名:通过pd.io.common.path.basename提取文件名,加入到结果数据中,方便对应分析结果和源文件
  • 合并数据:循环结束后用pd.concat把所有小DataFrame合并成一个大的DataFrame,ignore_index=True保证索引连续
  • 优化导出:设置index=False,避免Excel中出现多余的索引列

内容的提问来源于stack exchange,提问作者Sujith Kumar S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 15:36:19