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

相关推荐
小田学Python16 小时前
100行Python代码,搭一个能干活的AI Agent
python·langchain·大模型·ai agent
Csvn17 小时前
🐍 Day3 : Python 容器精讲 — list、dict、set、tuple 底层实现与高级操作
后端·python
weixin-a1530030831617 小时前
python-装饰器
开发语言·python
我的xiaodoujiao17 小时前
快速学习Python基础知识详细图文教程17--类型注解和断点调试
开发语言·python·学习·测试工具
每天吃饭的羊19 小时前
Chrome DevTools MCP
python
水獭比特20 小时前
localhost 不是安全边界:给 Agent Web 入口补上四层门禁
人工智能·python
Generalzy20 小时前
Whisper + VAD + TTS:一套完整的 Python 本地语音处理流水线
python·whisper·语音识别
qpsj20 小时前
让 LLM 控制 AutoCAD/ZWCAD:COM 自动化 + MCP 封装
python·llm
赟爸21 小时前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python
怪奇云呼军21 小时前
从声音特征到 CRM 回流:闪电智能 Voice Agent 沟通策略自适应系统 v1 实战
android·人工智能·python·音视频·语音识别