如何提取Pandas DataFrame行中列表元素的唯一匹配值至新列?
问题
我有一个存储职位招聘信息的DataFrame,其中Job_description列存储完整职位描述文本。为提取关键技能要求,我新增了Programming_Languages、Data_Visualisation列,分别对应待匹配的技能列表:
pl_list=['Python','RStudio','C#','HTML5'] dv_list=['Power BI','Tableau']
我原本使用str.findall进行匹配,但职位描述中同一个技能可能被多次引用,导致提取结果包含重复项,我需要每个匹配到的技能仅保留一次。
用于重现场景的代码:
import pandas as pd import re df = [ ['ABC','ABC','Python, C#, Power BI Tableau python Power BI'], ['ABC','ABC','Power BI Python'], ['ABC','ABC','Rstudio Rstudio Rstudio Tableau'], ['ABC','ABC','C# C# C# HTML5'] ] df = pd.DataFrame(df, columns=['Companyname', 'Jobtitle','Job_description']) df2 = df.reindex(df.columns.tolist() + ['Programming_Languages','Data_Visualisation'], axis=True)
原实现代码会返回重复值:
df2['Programming_Languages'] = df2['Job_description'].str.findall('|'.join(pl_list), re.IGNORECASE) df2['Data_Visualisation'] = df2['Job_description'].str.findall('|'.join(dv_list), re.IGNORECASE)
解决方案
方法1:去重+统一技能格式(推荐)
这个方法不仅会去重,还会将匹配结果的大小写统一为原技能列表中的格式(比如把匹配到的python转为Python,rstudio转为RStudio):
def extract_unique_skills(text, skill_list): # 匹配所有符合条件的技能,忽略大小写 matches = re.findall('|'.join(skill_list), text, re.IGNORECASE) # 创建技能大小写映射,用于统一格式 skill_case_map = {skill.lower(): skill for skill in skill_list} # 转集合去重,再转回列表 unique_skills = list({skill_case_map[match.lower()] for match in matches}) return unique_skills # 应用到对应列 df2['Programming_Languages'] = df2['Job_description'].apply(lambda x: extract_unique_skills(x, pl_list)) df2['Data_Visualisation'] = df2['Job_description'].apply(lambda x: extract_unique_skills(x, dv_list))
方法2:快速去重(不统一大小写)
如果不需要统一技能的大小写格式,直接对findall的结果转集合去重即可:
df2['Programming_Languages'] = df2['Job_description'].str.findall('|'.join(pl_list), re.IGNORECASE).apply(lambda x: list(set(x))) df2['Data_Visualisation'] = df2['Job_description'].str.findall('|'.join(dv_list), re.IGNORECASE).apply(lambda x: list(set(x)))
结果验证
运行方法1后,df2的核心结果如下:
| Companyname | Programming_Languages | Data_Visualisation |
|---|---|---|
| ABC | ['Python', 'C#'] | ['Power BI', 'Tableau'] |
| ABC | ['Python'] | ['Power BI'] |
| ABC | ['RStudio'] | ['Tableau'] |
| ABC | ['C#', 'HTML5'] | [] |
内容的提问来源于stack exchange,提问作者s.ara
相关产品推荐
相关产品推荐

