栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Excel文档内容对比(不区分大小写)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Excel文档内容对比(不区分大小写)

对两份Excel文档的内容进行比对,查看一份文档的记录是否存在于另一份文档中。



用Python来实现筛选匹配:

import openpyxl
import pandas as pd

path1 = r"C:UsersAdministratorDesktopfile1.xlsx"        #文档1
path2 = r"C:UsersAdministratorDesktopfile2.xlsx"        #文档2

#读取文件(读取文件时文件需要关闭)
file1 = pd.read_excel(path1)
file2 = pd.read_excel(path2)

for i in range(len(file1)):
	#获得file1中第i行各列的值
    site_short_name = file1.loc[i,'site_short_name']
    TOPIC_LV1 = file1.loc[i,'TOPIC_LV1']
    TOPIC_LV2 = file1.loc[i,'TOPIC_LV2']
    TOPIC_LV3 = file1.loc[i,'TOPIC_LV3']
    
    #查找file2中是否有符合全部条件的记录
    value = file2[(file2['TOPIC_LV1'] == TOPIC_LV1)&(file2['TOPIC_LV2'] == TOPIC_LV2)&(file2['TOPIC_LV3'] == TOPIC_LV3)]
    
    #判断value是否为空
    if len(value):
        file1.loc[i,'match'] = 'Y'    #如果不为空,则表示有符合条件的记录
    else:
        file1.loc[i,'match'] = 'N'

运行程序,查看匹配结果

#print(file1)

# 筛选查看“match”列为“Y”的记录
file1[file1['match']=='Y']

PS:想要不区分大小写时

for i in range(len(file1)):
	#casefold()强制将str转换为小写
    site_short_name = file1.loc[i,'site_short_name'].casefold()
    TOPIC_LV1 = file1.loc[i,'TOPIC_LV1'].casefold()
    TOPIC_LV2 = file1.loc[i,'TOPIC_LV2'].casefold()
    TOPIC_LV3 = file1.loc[i,'TOPIC_LV3'].casefold()
    
    #将dataframe转为str后再转为小写
    value = file2[(file2['TOPIC_LV1'].str.casefold() == TOPIC_LV1)&(file2['TOPIC_LV2'].str.casefold() == TOPIC_LV2)&(file2['TOPIC_LV3'].str.casefold() == TOPIC_LV3)]
    
    #判断value是否为空
    if len(value):
        file1.loc[i,'match'] = 'Y'    #如果不为空,则表示有符合条件的记录
    else:
        file1.loc[i,'match'] = 'N'
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/997419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号