Python Pandas在关键字 /句子上合并



我是Python的新手,我不知道如何解决以下问题:

我有两个数据范围,我想使用某种将句子与特定关键字匹配的vlookup函数。在下面的示例中,(DF1)3E句子应与香蕉(DF2)匹配,因为它在句子中包含香蕉。

import pandas as pd
df1 = pd.DataFrame({'Text': ['Some text 1', 'Some text 2','The monkey eats a banana','Some text 4']})
df2 = pd.DataFrame({'Keyword': ['apple', 'banana', 'chicken'], 'Type': ['fruit', 'fruit', 'meat']})
df1
    Text
0   Some text 1
1   Some text 2
2   The monkey eats a banana
3   Some text 4
df2
    Keyword Type
0   apple   fruit
1   banana  fruit
2   chicken meat

因此,可取的结果将是:

    Text                        Type
0   Some text 1                 -
1   Some text 2                 -
2   The monkey eats a banana    fruit
3   Some text 4                 -

我已经尝试使用合并和str.Contains函数,但是问题是香蕉在句子中而不是独立的值中。

使用 extract进行关键字,而 map将提取的"关键字"映射到" type"。

import re
p = rf"({'|'.join(map(re.escape, df2['Keyword']))})"
# p = '(' + '|'.join(map(re.escape, df2['Keyword'])) + ')'
df1['Type'] = (
    df1['Text'].str.extract(p, expand=False).map(df2.set_index('Keyword')['Type']))
df1
                       Text   Type
0               Some text 1    NaN
1               Some text 2    NaN
2  The monkey eats a banana  fruit
3               Some text 4    NaN

在哪里,

p
# '(apple|banana|chicken)'

最新更新