【问题标题】:fuzzywuzzy ratio of 2 columns if one column satisfies 100 percent match the best one如果一列满足 100% 匹配最佳一列,则两列的模糊模糊比率
【发布时间】:2016-08-28 19:20:52
【问题描述】:

我的数据框是

Matcher = df2['Account Name']

match = if df1['Billing Country'] == df2['Billing Country'] (process.extractOne(df1['Account Name'], Matcher))

上面的代码不起作用,但我只想在国家匹配时进行帐户名称的模糊匹配。

【问题讨论】:

  • 您可能应该对两个数据帧进行完全外连接,计算每个组合的 FuzzyRatio,并将结果过滤到只有 100% 匹配的那些。
  • Sam- 您是否建议我在 Billing country 上进行外部合并,然后查找每个组合的模糊匹配?

标签: python pandas fuzzywuzzy


【解决方案1】:

这就是我的建议。首先,在两个 dfs 上进行完整的笛卡尔连接:

df1.loc[:, 'MergeKey'] = 1 #create a mergekey
df2.loc[:, 'MergeKey'] = 1 #it is the same for both so that when you merge you get the cartesian product
#merge them to get the cartesian product (all possible combos)
merged = df1.merge(df2, on = 'MergeKey', suffixes = ['_1', '_2'])

然后,计算每个组合的模糊率:

def fuzzratio(row):
    try: #avoid errors for example on NaN's
        return fuzz.ratio(row['Billing Country_1'], row['Billing Country_2'])
    except:
        return 0. #you'll want to expiriment w/o the try/except too
merged.loc[:, 'Ratio'] = merged.apply(fuzzratio, axis = 1) #create ratio column by applying function

现在您应该有一个 df,其中包含 df1['Billing Country']df2['Billing Country'] 的所有可能组合之间的比率。到达那里后,只需过滤即可获得比率为 100% 的那些:

result = merged[merged.Ratio ==1]

【讨论】:

  • 对不起。我更难理解。您能否解释一下 df1.loc[:, 'MergeKey'] = 1 的作用。并且是 'MergeKey' 在此代码中是 'Account Name'
  • 我的代码是这个merged_file = pd.merge(df2, df1, on='Billing Country', how = 'outer')
  • 我有 3,467,624 个可能的匹配项,但我现在无法将其保存在 Excel 中。 merged_file.to_excel('merged_file.xlsx')
  • 我对合并键所做的是在每个 df 中创建一列 1。然后我加入这些专栏。这意味着,如果您在 df1 中有 10 行,在 df2 中有 10 行,那么您最终会在“合并”中得到 100 行。这将为您提供 Country_1 和 Country_2 的所有可能组合。然后你可以计算每个可能的组合的模糊率。
  • 如果您想查看另一对列的比率怎么办?你会添加另一个return语句吗?还是必须重写整个 def 语句?
【解决方案2】:

我的理解方式略有不同。

首先我合并使用

merged_file = pd.merge(df2, df1, on='Billing Country', how = 'left')

当我找到所有可能的匹配项时。

我应用了fuzzywuzzy的

`Reference_data= df2['Account Name']`

`Result = process.extractOne(df1, choices)`

因为上面的字符串为我想要查找的每个值提供了最接近的匹配项。 后来我又添加了一个字符串来计算比率。

Result['ratio']= fuzz.ratio(Result['Account Name_x'],Result['Account Name_y'] )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2019-04-05
    • 1970-01-01
    相关资源
    最近更新 更多