前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >利用Python实现Excel的文件间的数据匹配功能

利用Python实现Excel的文件间的数据匹配功能

作者头像
砸漏
发布2020-10-21 15:58:39
2.5K0
发布2020-10-21 15:58:39
举报
文章被收录于专栏:恩蓝脚本

我们知道Excel有一个match函数,可以做数据匹配。 比如要根据人名获取成绩

在这里插入图片描述
在这里插入图片描述

而参考表sheet1的内容如下:

在这里插入图片描述
在这里插入图片描述

要根据sheet1匹配每人的成绩,用Excel是这么写

index(Sheet1!B:B,MATCH(A2,Sheet1!A:A,0))

意思就是获取sheet1的B列的内容,根据我的A列匹配sheet1的A列的内容

但是如何用python实现这一点呢,我写了一个函数,非常好用,分享给大家。 这个函数考虑到了匹配多个字段,多个sheet。

代码语言:javascript
复制
import pandas as pd
def match(file,sheetnames,reffile,refsheet,targetsegs,matchseg)  #文件名 sheet列表 参考文件名 参考sheet 目标字段列表 参考字段
	alldata=pd.read_excel(file,None)
	refdata=pd.read_excel(reffile,refsheet)
	#获取映射字典
	maps={}
	for i in refdata.index:
		MatchSeg=refdata.loc[i,matchseg]
		maps[MatchSeg]={}
		for seg in targetsegs:
			maps[MatchSeg][seg]=refdata.loc[i,seg]
	#匹配数据
	for sheet in sheetnames:
		if(isinstance(sheet,int)):
			sheet=list(alldata.keys())[sheet]

		data=alldata[sheet].fillna('-')
		for i in data.index:
			MatchSeg=data.loc[i,matchseg]
			for seg in targetsegs:
				try:
					data.loc[i,seg]=map[MatchSeg][seg]
				except Exception as e:
					pass

		alldata[sheet]=data
	#导出
	with pd.ExcelWriter(file) as writer:
		for sheet in alldata.keys():
			alldata[sheet].to_excel(writer,sheet,index=False)
			
match('要匹配的表.xlsx',[0,1],'参考表.xlsx','参考页',['要匹配的字段1,字段2'],'参考字段')

总结

到此这篇关于利用Python实现Excel的文件间的数据匹配功能的文章就介绍到这了,更多相关Python实现Excel的文件间的数据匹配内容请搜索ZaLou.Cn以前的文章或继续浏览下面的相关文章希望大家以后多多支持ZaLou.Cn!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档