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

用Pandas合并含4行表头的Excel文件,仅保留第4行作为唯一表头

Pandas合并Excel文件:忽略重复表头并处理Unnamed列

问题背景

我正在处理格式统一的Excel文件,所有文件的前4行均为表头,只需要把第4行作为合并后文件的唯一表头。按教程用Pandas拼接后,2-4行重复出现在结果里,数据全乱了。

原代码:

import pandas as pd
import glob
location = '#path/*.xlsx'
excel_files = glob.glob(location)
df1 = pd.DataFrame()
for excel_file in excel_files:
    df2 = pd.read_excel(excel_file)
    df1 = pd.concat([df1, df2], ignore_index=True)
print(df1)
df1.to_excel('#path/excel_file_name.xlsx', index= False)

输出示例:

Col 1   Col2    Col3    Col4    Col5    Col6    Col7    Col8    Col9    Col10   Col11   Col12
                                
Item1   Item2   Item3   Item4   Item5   Item6   Item7   Item8   Item9   Item10  Item11  Item12
#Data From 1st file
Col 1   Col2    Col3    Col4    Col5    Col6    Col7    Col8    Col9    Col10   Col11   Col12
                                                
Item1   Item2   Item3   Item4   Item5   Item6   Item7   Item8   Item9   Item10  Item11  Item12
#Data From 2nd file
Col 1   Col2    Col3    Col4    Col5    Col6    Col7    Col8    Col9    Col10   Col11   Col12
                                                
Item1   Item2   Item3   Item4   Item5   Item6   Item7   Item8   Item9   Item10  Item11  Item12  
#etc

编辑补充:
试了修改循环后,只能读取第一个文件,表头还变成了Selected Criteria: Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 ETC...,得把这些“Unnamed: X”给清空。


解决方案

直接上修正后的代码,每一步都给你说明白:

import pandas as pd
import glob

location = '#path/*.xlsx'
excel_files = glob.glob(location)
df_list = []

for idx, excel_file in enumerate(excel_files):
    if idx == 0:
        # 第一个文件:指定第4行(索引3)作为表头,自动跳过前3行
        df = pd.read_excel(excel_file, header=3)
        # 处理Unnamed列:把带Unnamed的列名替换为空字符串
        df.columns = [col.replace('Unnamed: ', '') if 'Unnamed:' in col else col for col in df.columns]
        df_list.append(df)
    else:
        # 其他文件:跳过前4行表头,不自动设表头,沿用第一个文件的列名
        df = pd.read_excel(excel_file, skiprows=4, header=None)
        df.columns = df_list[0].columns
        df_list.append(df)

# 拼接所有数据
df_combined = pd.concat(df_list, ignore_index=True)
print(df_combined)
df_combined.to_excel('#path/excel_file_name.xlsx', index=False)

关键说明

  1. header=3的作用:Pandas的索引从0开始,第4行对应索引3,用这个参数直接把第4行设为DataFrame的列名,同时自动跳过前面3行,不用手动处理多余的表头行。
  2. 清理Unnamed列:用列表推导式遍历所有列名,只要列名里有Unnamed:,就把这个部分替换成空字符串,解决表头乱码问题。
  3. 其他文件的处理逻辑:用skiprows=4跳过全部4行表头,header=None告诉Pandas不要把读取到的第一行数据当成表头,然后手动把列名设置成和第一个文件一致,保证拼接时列完全对齐。
  4. 用enumerate代替index:之前用excel_files.index(excel_file)如果遇到重复文件名(虽然这里是路径,但万一有特殊情况)会出错,enumerate直接按循环顺序取索引,更稳定可靠。

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:45:39