Table of Contents
1. Problem description
2. Application method
3. Code writing
3.5
4. Code collection
Home Backend Development Python Tutorial How to classify the contents of two excel tables through python fuzzy matching algorithm

How to classify the contents of two excel tables through python fuzzy matching algorithm

May 28, 2023 am 08:43 AM
excel python

    1. Problem description

    During the internship, it is necessary to match and classify the contents of the two tables, such as for two different engineering projects The objects are all A, then these two engineering projects need to be classified into A. There are quite a lot of engineering projects and construction objects among them, so I thought of writing a program to automatically classify them. This can reduce a large part of the workload.

    2. Application method

    Since the two tables have similar keywords, that is, the content format of one table is project A, and the content format of the other table is unit A, then I just need to match the keyword "A" to filter it out. In this problem, I used a fuzzy matching algorithm to achieve my goal, but this algorithm is not the only possible solution.

    3. Code writing

    Note: Here we have imported the difflib library for using the fuzzy matching algorithm; the xlwt library for exporting excel tables

    3.1

    First we import the two excel tables that need to be processed.

    df1=pd.read_excel(r'D:\杂货\项目.xlsx',sheet_name='Sheet1')
    df2=pd.read_excel(r'D:\杂货\项目2.xlsx',sheet_name='Sheet1')#导入两个需要处理的excel表格
    Copy after login

    How to classify the contents of two excel tables through python fuzzy matching algorithm

    The content and format of the two tables are roughly as above. My requirement is to match and classify the engineering projects related to these two tables.

    3.2

    Put the two columns of data we want to process into a list.

    for i in df1['XXXXXX改造']:#将这两列的数据存入list1和list2两个列表中
        list1.append(i)
    for j in df2['XXXXXX新改']:
        list2.append(j)
    Copy after login

    3.3

    Use the fuzzy matching algorithm to match the data content in list2 with the data content in list1 one by one.

    for n in range(len(list2)):#通过模糊匹配算法,将list2与list1中的数据一一匹配,设置近似度为42%,得到匹配结果res
        query_word=str(list2[n])
        res=difflib.get_close_matches(query_word,list1,1,cutoff=0.42)
        res = "".join(res)
        listx.append(res)
    Copy after login

    It should be noted that the get_close_matches(query_word,list1,n,cutoff) method in the difflib library is called here, where query_word is the matched string; list1 is the list of strings to be matched. ; n is the return of the top n best matches, I set it to 1; cutoff is the matching degree, which is a floating point number in [0,1], which can also be called the degree of similarity between the two. This depends on personal needs. According to the specific problem, I set the similarity level to 0.42, which can successfully match the contents of the two tables that I need to match.

    Since every result matched by res is in the form of a list, and we want to write the results into a new table, we need the results in string form, so we use res="".join(res ) method converts the list into string form, and then puts the result in string form into the listx list to facilitate writing to a new excel table.

    3.4

    Because I was worried that there would be missing matching results, I matched the data content in list1 with the data content in list2 one by one.

    for m in range(len(list1)):#同上,将list1与list2的数据一一匹配
        query_word=str(list1[m])
        res=difflib.get_close_matches(query_word,list2,1,cutoff=0.42)
        res="".join(res)
        listy.append(res)
    Copy after login

    At this time, I set the matched string to the string in list1, and the string list to be matched to list2. The other parameters are the same, which is equivalent to saying that I first use table 1 to match table 2. , and then use Table 2 to match Table 1, so that the missing problem can be better solved.

    3.5

    Finally set the parameters of the new excel table

    workbook=xlwt.Workbook(encoding='utf-8')#设定好新的excel表格的参数
    worksheet=workbook.add_sheet('test_sheet')
    worksheet.write(0,0,label='XXX改造')#从第0行第0列开始输入标签为XXX改造的数据
    worksheet.write(0,1,label='XX金额')#从第0行第1列开始输入标签为XX金额的数据
    worksheet.write(0,2,label='XXX新改')
    worksheet.write(0,3,label='XX金额')
    worksheet.write(0,4,label='已XXX金额')
     
    for i in range(len(listx)):#写入运算出来的数据
        worksheet.write(i+1,0,label=listx[i])
    for j in range(len(listy)):
        worksheet.write(j+1,2,label=listy[j])
    for k in range(len(list1)):
        worksheet.write(k+1,1,label=list3[k])
    for l in range(len(list2)):
        worksheet.write(l+1,3,label=list4[l])
        worksheet.write(l+1,4,label=list5[l])
    workbook.save(r'D:\杂货\新项目6.xls')#导出excel表格
    Copy after login

    The method used here to write data content into the excel table will not be introduced in detail. People who have experience working with excel can easily understand the meaning of the code.

    The final output table format is as follows:

    How to classify the contents of two excel tables through python fuzzy matching algorithm

    # After two passes of matching, those with a high degree of mutual matching will appear in the table accordingly. , and if there is only a single high degree of matching, there will be data on the left but no data on the right, or there will be data on the right but no data on the left.

    4. Code collection

    import pandas as pd
    import difflib
    import xlwt#导入库
     
    df1=pd.read_excel(r'D:\杂货\项目.xlsx',sheet_name='Sheet1')
    df2=pd.read_excel(r'D:\杂货\项目2.xlsx',sheet_name='Sheet1')#导入两个需要处理的excel表格
     
    list1=[]#设置空列表,用于存储2017年一列的数据
    list2=[]#用于存储2018年一列的数据
    list3=list(df1['XX金额'])#将excel表格中的列数据列表化
    list4=list(df2['XX金额'])
    list5=list(df2['XXX金额'])
    listx=[]#用于存储匹配结果的数据
    listy=[]#同上
    for i in df1['XXXXXXXXX改造']:#将这两列的数据存入list1和list2两个列表中
        list1.append(i)
    for j in df2['XXXXXXXXXXXXX新改']:
        list2.append(j)
     
    for n in range(len(list2)):#通过模糊匹配算法,将list2与list1中的数据一一匹配,设置近似度为42%,得到匹配结果res
        query_word=str(list2[n])
        res=difflib.get_close_matches(query_word,list1,1,cutoff=0.42)
        res = "".join(res)
        listx.append(res)
     
    for m in range(len(list1)):#同上,将list1与list2的数据一一匹配
        query_word=str(list1[m])
        res=difflib.get_close_matches(query_word,list2,1,cutoff=0.42)
        res="".join(res)
        listy.append(res)
     
    workbook=xlwt.Workbook(encoding='utf-8')#设定好新的excel表格的参数
    worksheet=workbook.add_sheet('test_sheet')
    worksheet.write(0,0,label='XXXXXXXXX改造')
    worksheet.write(0,1,label='XX金额')
    worksheet.write(0,2,label='XXXXXXXXXXX新改')
    worksheet.write(0,3,label='XX金额')
    worksheet.write(0,4,label='XXX金额')
     
    for i in range(len(listx)):#写入运算出来的数据
        worksheet.write(i+1,0,label=listx[i])
    for j in range(len(listy)):
        worksheet.write(j+1,2,label=listy[j])
    for k in range(len(list1)):
        worksheet.write(k+1,1,label=list3[k])
    for l in range(len(list2)):
        worksheet.write(l+1,3,label=list4[l])
        worksheet.write(l+1,4,label=list5[l])
    workbook.save(r'D:\杂货\新项目6.xls')#导出excel表格
    Copy after login

    The above is the detailed content of How to classify the contents of two excel tables through python fuzzy matching algorithm. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    Java Tutorial
    1664
    14
    PHP Tutorial
    1269
    29
    C# Tutorial
    1249
    24
    PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

    PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

    Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

    PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

    How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

    To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

    PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

    PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

    Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

    Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

    Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

    Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

    How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

    Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

    See all articles