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

相关推荐
2601_962078192 小时前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
2601_962218612 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_966949652 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
2601_962885722 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
李高钢3 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
ocean21033 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文
Warson_L3 小时前
Python的OrderedDict
python
隐擎fox3 小时前
高性能网络爬虫架构设计:基于 Python 的长连接复用与分布式会话池调度实践
分布式·python·网络协议·tcp/ip·高并发·网络爬虫、
Warson_L3 小时前
Python的TypedDict
python·langchain·llm
晓窗科技4 小时前
口碑好的AI基座服务商
大数据·人工智能·python