使用Python合并excel表——简单

本文介绍如何使用Python的pandas库合并多个Excel文件。提供两种方法:一种是直接指定要合并的文件,适合少量文件;另一种是自动合并指定路径下的所有Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 说明

        主要是在记录怎么使用pyhon语言操作excel表格,实现对多个excel表格的合并,方法特别简单,当然也有点笨(😔)。

2 代码

简单版

# 简单版:直接指定读取文件的个数与名称,扩展性差
import pandas as pd

# 解决数据输出时列明不对齐的问题
pd.set_option('display.unicode.ambiguous_as_wide',True)
pd.set_option('display.unicode.east_asian_width',True)

dfs = [] # 存数读取的文件


df = pd.read_excel("露点温度.xls", index_col=0) # index_col是以某一列为名
dfs.append(df)
df = pd.read_excel("风速&压强.xls", index_col=0) # index_col是以某一列为名
dfs.append(df)

result1 = pd.concat(dfs) # 默认按照列合并
result2 = pd.concat(dfs,axis=1) # axis=1,按照行进行合并

result1.to_excel("result1.xls")
result2.to_excel("result2.xls")

稍微复杂版

# 稍微复杂点的
import pandas as pd
import os

filePath = input("请输入待合并文件的路径:") # 设置工作路径,例如D:\Program\files,尽量不要是中文路径
# 解决数据输出时列明不对齐的问题
pd.set_option('display.unicode.ambiguous_as_wide',True)
pd.set_option('display.unicode.east_asian_width',True)

dfs = []
# dirs是root下的所有目录,files是root下的所有文件
for root, dirs, files in os.walk(filePath):  # 返回三元组
    for file in files:  # 遍历文件
        # os.path.join(root,file)root/file 拼接文件路径并读取excel文件
        df = pd.read_excel(os.path.join(root,file))
        dfs.append(df)
# 合并所有数据
result3 = pd.concat(dfs)
result4 = pd.concat(dfs,axis=1)
# 导出excel
result3.to_excel("result3.xls",index=False)
result4.to_excel("result4.xls",index=False)
print("合并成功!")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

B or D

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值