如何用Pandas处理带有合并列标题的Excel文件?
处理Pandas读取合并列标题Excel的问题
直接用以下步骤就能解决:
读取Excel时指定多级表头
原文件的表头是两行结构,读取时指定header=[0,1],让Pandas把前两行都识别为表头:import pandas as pd # 替换成你的文件路径 df = pd.read_excel("your_file.xlsx", header=[0, 1])合并多级表头为单级标题
读取后会得到多级列名,其中合并单元格对应的上层表头为空,我们需要把上层和下层标题合并,空的上层标题继承左侧的有效标题: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
相关产品推荐
相关产品推荐

