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

相关推荐
l1t20 分钟前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
Cemtery1162 小时前
Day26 常见的降维算法
人工智能·python·算法·机器学习
星空椰3 小时前
快速掌握FastAPI:高效构建Web API
python·fastapi
塔尖尖儿3 小时前
Python中range()到底是什么演示
python
Ethan-D4 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
weixin_446934035 小时前
统计学中“in sample test”与“out of sample”有何区别?
人工智能·python·深度学习·机器学习·计算机视觉
weixin_462446236 小时前
使用 Python 测试 Mermaid 与 Graphviz 图表生成(支持中文)
python·mermaid·graphviz
JOBkiller1236 小时前
钢绞线缺陷检测与识别_Cascade-Mask-RCNN_RegNetX模型训练与应用实战
python
nvd116 小时前
深入 ReAct Agent 的灵魂拷问:从幻觉到精准执行的调试实录
python·langchain