python - 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 函数,但是,问题是香蕉在句子中不是独立值。
解决方案
用于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)'
推荐阅读
- firebase - Firebase 提供商登录在 facebook/messenger/instagram 应用内浏览器 webview 中不起作用。错误 403:disallowed_useragent
- linux-kernel - 如何使用 linux 内核 5.6.x 中包含的 MPTCP?
- python - Django rest 框架中的 self.get_serializer 和 Serializer 对象有什么区别?
- codeigniter - Codeigniter - 如何使用 $data[] 传递和覆盖变量
- c++ - c++替换调用对象方法的宏函数
- python-3.x - 在 DataFrame 中的列上调用 Python 函数
- angular - 在模板中存储 Observable 的解析值以供多次使用
- javascript - 文档和集合参考之间的区别
- digital-ocean - 错误损坏的标头:“在 Kubernates 上使用 LetsEncrypt 获取 /.well-known/acme-challeng
- python - Python 字典更新在 for 循环中不起作用