python - Pandas 匹配列表中的元素

标签 python pandas

我需要将 pandas 列中列出的关键字与列表中的关键字进行匹配,并创建一个包含匹配词的新列。示例:

my_list = ['machine learning', 'artificial intelligence', 'lasso']

数据:

listing                                         keyword_column
I am looking for machine learning expert        machine learning
Machine learning expert that knows lasso        machine learning, lasso
Need a web designer                              
Artificial Intelligence application on...       artificial intelligence

最佳答案

使用Series.str.findall要获取列表中的所有值,请按 Series.str.join 连接在一起如有必要,通过 Series.str.lower 转换为小写字母:

这里还使用了带有 \b 的单词边界,用于正确匹配 my_list 中的整个单词。

my_list = ['machine learning', 'artificial intelligence', 'lasso']

import re

pat = '|'.join(r"\b{}\b".format(x) for x in my_list)
df['new'] = df['listing'].str.findall(pat, flags=re.I).str.join(', ').str.lower()

或者:

df['new'] = df['listing'].str.lower().str.findall(pat).str.join(', ')

print (df)
                                    listing           keyword_column  \
0  I am looking for machine learning expert         machine learning   
1  Machine learning expert that knows lasso  machine learning, lasso   
2                      Need a web designer                       NaN   
3    Artificial Intelligence application on  artificial intelligence   

                       new  
0         machine learning  
1  machine learning, lasso  
2                           
3  artificial intelligence  

关于python - Pandas 匹配列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752417/

相关文章:

python - Pandas 滚动 OLS 被弃用

python - 如何在列表中运行我的标记器函数 - 模块对象不可调用?

java - Pexpect 相当于 java 吗?

python - Plotly:如何避免巨大的 html 文件大小

pandas - 类型错误 : unhashable type: 'numpy.ndarray' - How to get data from data frame by querying radius from ball tree?

python-2.7 - 在 Python 中根据值查找 Pandas 数据框列

python - 如何迭代 Pandas 中的 MultiIndex 级别?

python - 这个 "if"语句是什么意思?

python - 给定一个 (Python) Selenium WebElement,我可以获得 innerText 吗?

python - 按钮颜色在功能中不改变 (Python tkinter)