利用Python实现Excel的文件间的数据匹配功能
作者:chaodaibing 时间:2023-12-04 19:53:42
我们知道Excel有一个match函数,可以做数据匹配。
比如要根据人名获取成绩
而参考表sheet1的内容如下:
要根据sheet1匹配每人的成绩,用Excel是这么写
index(Sheet1!B:B,MATCH(A2,Sheet1!A:A,0))
意思就是获取sheet1的B列的内容,根据我的A列匹配sheet1的A列的内容
但是如何用python实现这一点呢,我写了一个函数,非常好用,分享给大家。
这个函数考虑到了匹配多个字段,多个sheet。
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'],'参考字段')
来源:https://blog.csdn.net/chaodaibing/article/details/106719083
标签:Python,Excel,数据匹配
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 线程池模块之多线程操作代码
2022-06-14 06:01:47
Python request设置HTTPS代理代码解析
2023-01-15 00:48:24
Jupyter notebook中5个有趣的魔法命令分享
2021-11-28 23:26:30
![](https://img.aspxhome.com/file/2023/5/78695_0s.png)
以实例全面讲解PHP中多进程编程的相关函数的使用
2023-10-18 12:21:55
提高ASP性能的最佳选择第一部分
2007-08-15 12:31:00
一文教你如何用Python轻轻松松操作Excel,Word,CSV
2021-11-20 22:47:52
![](https://img.aspxhome.com/file/2023/9/107109_0s.png)
一些关于asp 购物车的想法
2011-04-10 11:10:00
详解vue事件对象、冒泡、阻止默认行为
2024-04-28 09:26:19
Python查找第n个子串的技巧分享
2023-02-20 22:02:55
js星级评分代码
2008-05-02 21:07:00
![](https://img.aspxhome.com/file/UploadPic/20085/2/star_78s.gif)
解决python3运行selenium下HTMLTestRunner报错的问题
2022-04-14 16:44:19
Python flask与fastapi性能测试方法介绍
2022-12-07 00:10:17
利用Opencv中Houghline方法实现直线检测
2023-09-07 12:40:39
![](https://img.aspxhome.com/file/2023/0/84000_0s.png)
Python+radar实现随机日期时间的生成
2021-04-16 23:22:57
![](https://img.aspxhome.com/file/2023/2/134682_0s.jpg)
Python三目运算符(三元运算符)用法详解(含实例代码)
2022-08-10 19:59:59
详解如何让Go语言中的反射加快
2024-05-28 15:36:52
Python性能分析工具py-spy原理用法解析
2021-08-30 14:57:23
![](https://img.aspxhome.com/file/2023/1/89441_0s.png)
Pandas缺失值填充 df.fillna()的实现
2023-11-24 00:01:41
![](https://img.aspxhome.com/file/2023/3/95903_0s.png)
python3.7简单的爬虫实例详解
2023-06-30 15:55:13
python列表中remove()函数的使用方法详解
2021-05-13 22:52:46
![](https://img.aspxhome.com/file/2023/8/94058_0s.png)