Python之Excel合并

大家好!今天我们要一起探索如何使用Python这个神奇的工具,将一堆Excel文件轻松合并成一个大文件。想象一下,就像是一台高效的Excel数据收割机,让你的工作效率飙升!准备好你的笔记本,跟着我一步步操作吧。

1. 导入所需库

首先,我们需要导入两个Python库:pandasospandas 是数据分析的大杀器,而 os 则帮我们处理文件和目录操作。

python 复制代码
import pandas as pd
import os

2. 定义函数:读取Excel文件

接下来,我们要创建一个函数 read_excel_files(),它会遍历指定目录下的所有Excel文件,并读取内容。

python 复制代码
def read_excel_files(directory):
    excel_files = [f for f in os.listdir(directory) if f.endswith('.xlsx') or f.endswith('.xls')]
    data_frames = []
    for file in excel_files:
        df = pd.read_excel(os.path.join(directory, file))
        data_frames.append(df)
    return data_frames

3. 合并数据

现在有了读取文件的函数,我们可以用另一个函数 merge_dataframes() 来合并所有数据帧。

python 复制代码
def merge_dataframes(data_frames):
    merged_df = pd.concat(data_frames, ignore_index=True)
    return merged_df

ignore_index=True 是为了确保合并后的行索引从0开始,这样看起来更清爽。

4. 写入新Excel文件

最后,我们来一个"一键合并"操作,把所有数据写入新的Excel文件。

python 复制代码
def write_to_excel(merged_df, output_file):
    merged_df.to_excel(output_file, index=False)

5. 实战演练

现在,把这些函数串起来用一个简单的例子展示:

python 复制代码
# 指定要读取的文件夹路径
input_dir = 'your_directory_with_excel_files'

# 创建一个新的Excel文件保存结果
output_file = 'merged_data.xlsx'

# 读取文件、合并数据并写入新文件
all_data = read_excel_files(input_dir)
merged_data = merge_dataframes(all_data)
write_to_excel(merged_data, output_file)

print(f"恭喜你,所有数据已合并到'{output_file}'!")

记得将 your_directory_with_excel_files 替换为你实际存放Excel文件的文件夹路径。

就这样,通过Python,你不再需要手动一个接一个地打开和粘贴数据了。这不仅提高了效率,还能避免因为手动操作可能出现的错误。快去试试看吧,让你的Excel数据管理变得更简单、更有趣!

相关推荐
m0_734949796 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
t***5447 小时前
Clang 编译器在 Orwell Dev-C++ 中的局限性
开发语言·c++
m0_514520577 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
H Journey7 小时前
Python 国内pip install 安装缓慢
python·pip·install 加速
oy_mail7 小时前
QoS质量配置
开发语言·智能路由器·php
oyzz1207 小时前
PHP操作redis
开发语言·redis·php
nashane8 小时前
HarmonyOS 6学习:网络能力变化监听与智能提示——告别流量偷跑,打造贴心网络感知应用
开发语言·php·harmony app
Polar__Star8 小时前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
凌波粒8 小时前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
m0_743623929 小时前
React 自定义 Hook 的命名规范与调用规则详解
jvm·数据库·python