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

相关推荐
雕刻刀9 分钟前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
何双新10 分钟前
Odoo 技术演进全解析:从 Widget 到 Owl,从 Old API 到声明式 ORM
python
山川行37 分钟前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
星辰徐哥42 分钟前
C语言游戏开发:Pygame、SDL、OpenGL深度解析
c语言·python·pygame
xcLeigh1 小时前
Python入门:Python3基础练习题详解,从入门到熟练的 25 个实例(六)
开发语言·python·教程·python3·练习题
不懒不懒1 小时前
安装python3.9.7和pycharm-community-2022.3.2.exe以及linux
linux·ide·python·pycharm
Jasonakeke1 小时前
我的编程来时路
java·c++·python
Yvonne爱编码1 小时前
Java 中的 hashCode () 与 equals () 核心原理、契约规范、重写实践与面试全解
java·开发语言·数据结构·python·hash
HappyAcmen1 小时前
理解Python中的global与nonlocal
python
测试老哥2 小时前
Web自动化测试:Cypress 测试框架概述
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例