如何使用 Python 对 Pandas 数据帧列进行模糊匹配?


我们将在第一个数据帧中匹配的行与第二个数据帧中的单词进行匹配。对于最为接近的匹配,我们将使用阈值。我们将阈值设为 70,即,当字符串之间的相似度达到 70% 以上时,才发生匹配。

让我们首先创建字典并转换为 panda 数据帧 −

# dictionaries
d1 = {'Car': ["BMW", "Audi", "Lexus", "Mercedes", "Rolls"]}

d2 = {'Car': ["BM", "Audi", "Le", "MERCEDES", "Rolls Royce"]}

# convert dictionaries to pandas dataframes
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

现在,将数据帧列转换为元素列表以便进行模糊匹配 −

myList1 = df1['Car'].tolist()
myList2 = df2['Car'].tolist()

示例

以下为完整代码 −

import pandas as pd
from fuzzywuzzy import fuzz
from fuzzywuzzy import process

# dictionaries
d1 = {'Car': ["BMW", "Audi", "Lexus", "Mercedes", "Rolls"]}

d2 = {'Car': ["BM", "Audi", "Le", "MERCEDES", "Rolls Royce"]}

# convert dictionaries to pandas dataframes
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# printing the pandas dataframes
print("Dataframe 1 = 
",df1) print("Dataframe 2 =
",df2) # empty lists for storing the matches later match1 = [] match2 = [] k = [] # converting dataframe column to list of elements for fuzzy matching myList1 = df1['Car'].tolist() myList2 = df2['Car'].tolist() threshold = 70 # iterating myList1 to extract closest match from myList2 for i in myList1:    match1.append(process.extractOne(i, myList2, scorer=fuzz.ratio)) df1['matches'] = match1 for j in df1['matches']:    if j[1] >= threshold:       k.append(j[0])    match2.append(",".join(k))    k = [] # saving matches to df1 df1['matches'] = match2 print("
Matches...") print(df1)

输出

将产生以下输出 −

Dataframe 1 =
       Car
0      BMW
1     Audi
2    Lexus
3 Mercedes
4    Rolls
Dataframe 2 =
           Car
0          BM
1        Audi
2          Le
3    Mercedes
4 Rolls Royce

Matches...
        Car matches
0       BM       BM
1     Audi     Audi
2    Lexus
3 Mercedes MERCEDES
4    Rolls

更新时间: 09-Sep-2021

2K+ 浏览量

开启您的 职业 生涯

完成课程并获得认证

开始学习
广告