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

如何用Pandas处理带有合并列标题的Excel文件?

处理Pandas读取合并列标题Excel的问题

直接用以下步骤就能解决:

  1. 读取Excel时指定多级表头
    原文件的表头是两行结构,读取时指定header=[0,1],让Pandas把前两行都识别为表头:

    import pandas as pd
    
    # 替换成你的文件路径
    df = pd.read_excel("your_file.xlsx", header=[0, 1])
    
  2. 合并多级表头为单级标题
    读取后会得到多级列名,其中合并单元格对应的上层表头为空,我们需要把上层和下层标题合并,空的上层标题继承左侧的有效标题:

    new_columns = []
    last_valid_top = None
    
    for top, bottom in df.columns:
        # 上层标题为空时,沿用左侧的上层标题
        if pd.isna(top):
            current_top = last_valid_top
        else:
            current_top = top
            last_valid_top = current_top
        # 拼接成新列名,格式可根据需求调整
        new_columns.append(f"{current_top}-{bottom}")
    
    # 替换原列名
    df.columns = new_columns
    
    # 重置索引(可选,根据需求调整)
    df = df.reset_index(drop=True)
    

这样处理后,列名就会变成你期望的总评分-评分1、总评分-评分2这类格式,和目标输出一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:50:32