首页 > 解决方案 > 如何检查列表和 DF 的记录之间是否匹配,并根据匹配的存在返回匹配的值

问题描述

我正在寻找测试以查看我的 DF 中的一个字段是否包含我定义的列表中也包含的年份。如果有匹配项,我想在我的数据框中标题为“年份”的新列中返回年份

我的输入:

#List of Years that I am scanning the data for

years = str((list(range(1970,2021))))

#Code to scan the field in my DF for a match and return the matching value if it exists. I am currently getting an error upon running this line.

string = posts['title']

for i in years:
    posts['year'] = string.str.extract('(' + '|'.join(years) + ')')
    

总的来说,我希望我的输出如下所示

ID 文本
1234 我想要一辆 2004 年的法拉利 2004年
1235 我很想拥有一辆保时捷

标签: pythonpandasstringdataframetext-extraction

解决方案


你是在正确的方向,除了你不需要循环:

years = "|".join(map(str,range(1970,2021)) )

df['year'] = df.text.str.extract(f'({years})')

输出:

     id                             text  year
0  1234           i want a 2004 ferrari   2004
1  1235  i would love to have a porsche    NaN

推荐阅读