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

如何用Python计算多子文件夹merged.txt的行中位数并统一表头?

批量合并多表格并计算行中位数的解决方案

这是个很典型的批量表格处理场景,用Python脚本就能轻松搞定,我给你整理了一套完整的解决方案,包括思路和可直接运行的代码:

核心实现思路

  1. 自动遍历目标目录:找到所有子文件夹里的merged.txt文件;
  2. 统一列名映射:把带后缀的列名(比如a_a、a_b)转换成统一的目标列名(比如a);
  3. 按行收集对应数据:针对每个行名(比如std),收集所有文件中对应列的数值;
  4. 计算中位数并输出:对每行的每列数据计算中位数,生成你需要的格式表格。

可直接运行的代码

import os
import pandas as pd
import numpy as np

# 替换成你的根目录路径(所有子文件夹的上级目录)
root_dir = "./"

# 先遍历一次,收集所有行名和目标列名
row_names = set()
target_cols = set()

for subdir, _, files in os.walk(root_dir):
    for file in files:
        if file == "merged.txt":
            df = pd.read_csv(os.path.join(subdir, file), sep=",")
            row_names.update(df.iloc[:, 0].tolist())
            # 提取统一列名(下划线前的部分)
            for col in df.columns[1:]:
                target_cols.add(col.split("_")[0])

# 初始化数据结构:按行名+目标列收集所有数值
row_data = {row: {col: [] for col in target_cols} for row in row_names}

# 二次遍历,填充数据
for subdir, _, files in os.walk(root_dir):
    for file in files:
        if file == "merged.txt":
            df = pd.read_csv(os.path.join(subdir, file), sep=",")
            for idx, row in df.iterrows():
                current_row_name = row["stat"]
                for col in df.columns[1:]:
                    target_col = col.split("_")[0]
                    row_data[current_row_name][target_col].append(row[col])

# 计算中位数,构造结果表格
result_rows = []
for row_name in sorted(row_names):
    median_vals = {"stat": row_name}
    for col in sorted(target_cols):
        median_vals[col] = np.median(row_data[row_name][col])
    result_rows.append(median_vals)

result_df = pd.DataFrame(result_rows)

# 输出到控制台(和你要的格式完全一致)
print(result_df.to_csv(sep=",", index=False))
# 如果要保存到文件,取消下面注释
# result_df.to_csv("final_median.csv", sep=",", index=False)

关键细节说明

  • 列名适配:代码默认用下划线分割列名提取统一名称,如果你的列名是其他分隔规则,只需要修改col.split("_")[0]这一行即可(比如改成col.split("-")[0]);
  • 行名兼容:如果各个文件的行名不完全一致,代码会自动保留所有行名并单独计算对应中位数;
  • 依赖安装:运行前需要先安装依赖库,执行pip install pandas numpy即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:42:45