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

Python 3.11合并多Excel文件:如何避免列重复?

问题与解决方案

问题描述

我编写了一段Python脚本,用于合并多个仅包含Alpha、number两列的Excel文件,文件格式示例如下:

Alpha number
  a    1
  b    2
  c    3

但输出文件却出现了六列,求修改代码实现两列的正确合并(避免重复列)。当前使用的代码如下:

import pandas as pd
import os

path =  "/Users/shoug/Desktop/ShouqTest"
os.chdir(path)

listOfFiles = os.listdir(path)

##listOfFiles=os.listdir(path)
##if '.DS_Store' in listOfFiles:
  ##listOfFiles.remove('.DS_Store')

df = pd.DataFrame()
print(df.shape) 

for entry in listOfFiles:
    print(entry)
    dfx = pd.read_excel(entry)
    dfx['Template'] = entry[:-17]
    ##df = df.append(dfx)
    df= pd.concat([df, dfx], axis= 1)
    print(df.shape)

df = df.drop_duplicates()
cols = [0,1]
df = df[df.columns[cols]]
df.to_excel(path + '_combined.xlsx', index = False)

错误原因

核心问题是你用了pd.concat([df, dfx], axis=1),这是横向按列拼接,会把每个文件的所有列依次追加到右侧,多个文件叠加后自然会出现重复列。正确的合并方式应该是纵向按行拼接,把每个文件的行数据追加到下方,保持列数一致。

另外代码还存在两个小问题:

  1. 没有过滤非Excel文件(比如Mac系统的.DS_Store),可能导致读取错误
  2. 最后手动筛选前两列的逻辑不合理,会丢失Template列或其他需要的内容

修改后的代码

import pandas as pd
import os

path = "/Users/shoug/Desktop/ShouqTest"
os.chdir(path)

# 只保留xlsx格式文件,排除.DS_Store
listOfFiles = [file for file in os.listdir(path) if file.endswith('.xlsx') and file != '.DS_Store']

df_combined = pd.DataFrame()

for file in listOfFiles:
    print(f"正在处理文件: {file}")
    # 读取单个Excel文件
    df_single = pd.read_excel(file)
    # 添加来源文件标记列(不需要可删除此行)
    df_single['Template'] = file[:-17]
    # 纵向拼接数据,ignore_index重置索引避免重复
    df_combined = pd.concat([df_combined, df_single], axis=0, ignore_index=True)

# 按需去重(不需要可删除此行)
df_combined = df_combined.drop_duplicates()

# 保存合并后的文件,用os.path.join避免路径拼接错误
df_combined.to_excel(os.path.join(path, 'combined.xlsx'), index=False)

关键修改说明

  • 将pd.concat的axis=1改为axis=0,实现纵向行拼接,保持列数不变
  • 添加ignore_index=True,重置合并后的索引,避免出现重复索引
  • 新增文件过滤逻辑,只处理有效Excel文件,避免读取无关文件报错
  • 用os.path.join拼接输出路径,比直接字符串拼接更兼容不同系统
  • 保留了Template列的添加逻辑,若不需要可直接删除对应行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:07:25