Python将两个Excel文件按相同字段合并到一起

在工作中我们需要将两个有关联的数据文件合并成一个Excel

1. 创建两个excel文件

test1

test2

2. 使用Pandas 数据分析工具进行合并

Pandas 一个强大的分析结构化数据的工具集,提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)

python 复制代码
import pandas as pd

file1 = pd.read_excel('test1.xlsx')
file2 = pd.read_excel('test2.xlsx')

# 根据ID字段将file1和file2合并到一起,并将结果保存在merged_file变量
merged_file = pd.merge(file1, file2, on='id')

# 将合并后的结果保存到新的Excel文件中
merged_file.to_excel('merged_file.xlsx', index=False)

print("文件合并完成!")
复制代码
merged_file.to_excel('merged_file.xlsx', index=False);
index=False:不会将 DataFrame 的索引写入 Excel 文件。Excel 文件中将只有 DataFrame 的列,而没有索引列

3. 运行成功后显示新创建的Excel

相关推荐
明知道的博客7 分钟前
解决WSL环境下DeepSeek-OCR运行时内存不足问题
python·ocr·deepseek·deepseek-ocr
FreeCode1 小时前
LangGraph1.0智能体开发:Graph API概念与设计
python·langchain·agent
test管家1 小时前
如何在Python中使用SQLite数据库进行增删改查操作?
python
yangmf20403 小时前
APM(三):监控 Python 服务链
大数据·运维·开发语言·python·elk·elasticsearch·搜索引擎
yangmf20403 小时前
APM(二):监控 Python 服务
大数据·python·elasticsearch·搜索引擎
CoderJia程序员甲3 小时前
GitHub 热榜项目 - 日榜(2025-11-23)
python·开源·github·mcp
AI爱好者3 小时前
WordPress保卫战:用Python分析日志并封禁恶意爬虫
python
nvd114 小时前
Gidgethub 使用指南
开发语言·python
___波子 Pro Max.4 小时前
Python模块导入详解与最佳实践
python
CNRio5 小时前
ZUC国密算法深度研究:原理、实现与应用(Python、Rust)
python·算法·rust