查找两个数据帧之间的字符串匹配

时间:2018-10-11 11:43:02

标签: python string pandas dataframe

我有一个如下所示的DataFrame。

DF1:

   A
Any Match
Credit
I need a debit card.
Logging
Awesome

我还有另一个DataFrame,如下所示:

DF2:

          B
I did not find any match.
I want a credit card.
I need a debit card.
I do not know.
I am logging into credit portal.

我需要输出为:

              B                           A
     I did not find any match.        Any Match
     I want a credit card.            Credit
     I need a debit card.             I need a debit card.
     I am logging into credit portal. logging,credit

如果DF1中存在的短语在DF2中存在的任何文本中,则为

。 将o / p打印为“文本”和重要短语。

3 个答案:

答案 0 :(得分:0)

尝试Fuzzywuzzy

import pandas as pd
from fuzzywuzzy import fuzz

matched_entities = []

for row in df1.index:
    name1 = vendor_df.get_value(row,"A")
    for columns in df2.index:
        name2=df2.get_value(columns,"B")
        matched_token=fuzz.partial_ratio(name1,name2)
        if matched_token> 80:
            matched_vendors.append([A,B])

df_partial_ratio = pd.DataFrame(columns=['A', 'B'], data=matched_entities)

在您的数据库中,如果fuzz.partial_ratio不起作用,请尝试fuzz.ratiofuzz.token_sort_ratio。可以通过将以下代码中的一行更改为以下代码来实现这两项:

matched_token=fuzz.ratio(name1,name2)

OR

matched_token=fuzz.token_sort_ratio(name1,name2)

答案 1 :(得分:0)

您可以执行以下操作。首先,定义与“规范化”文本匹配的查找功能,例如小写:

def lookup(x, values):
    for value in values:
        if value.lower() in x.lower():
            return value

然后将此功能应用于DF2:

dfB['A'] = dfB['B'].apply(lambda x: lookup(x, dfA['A']))

哪些应该给您:

    B                           A
0   I did not find any match.   Any Match
1   I want a credit card.       Credit
2   I need a debit card.        Debit
3   I do not know.              None

答案 2 :(得分:0)

尝试

df1['B'] = float('nan')

pos = 0
for i in range(len(df1)):
    for j in range(len(df2)):
        if df1['A'][i].lower() in df2['B'][j].lower():
            df1['B'].iloc[pos] = df2['B'][j]
            pos+=1
            break

df1.dropna(axis=0)

输出

                     A                          B
0            Any Match  I did not find any match.
1               Credit      I want a credit card.
2  I need a debit card       I need a debit card.