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

相关推荐
statistican_ABin21 分钟前
WHO各国预期寿命影响因素分析与轻量回归预测
大数据·人工智能·python·数据分析·回归
卷无止境1 小时前
Python生成器与惰性求值:从yield说起的一场"暂停魔法"
后端·python
卷无止境1 小时前
从一个装饰器说起:拆解 Python 的 @property
后端·python
农村小镇哥1 小时前
python操作配置文件ini
开发语言·python
love530love9 小时前
OpenClaw Windows Companion 桌面客户端 连接 LM Studio 完整配置指南
人工智能·windows·python·openclaw
cui_ruicheng11 小时前
Python从入门到实战(十六):多进程编程
开发语言·python
_Jimmy_13 小时前
FastAPI + SQLAlchemy全局事务管理
python·fastapi
用户83562907805113 小时前
如何使用 Python 在 Excel 中添加、编辑和删除超链接
后端·python
AC赳赳老秦15 小时前
企业工商公开信息采集分析:OpenClaw 批量查询企业工商信息,生成企业画像报告
大数据·开发语言·python·自动化·php·deepseek·openclaw
FoldWinCard15 小时前
D6 Python 基础语法 --- 保留关键字
开发语言·python