首页 > 解决方案 > 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                 -

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

标签: pythonpandasmatchvlookup

解决方案


用于extract关键字,并将map提取的“关键字”映射到“类型”。

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)'

推荐阅读