How to check if there is a match between a list and a record of a DF, and based on the presence of a match return the matched value

Viewed 50

I am looking to test to see if a field in my DF contains a year that is also contained in a list I have defined. If there is a match, i would like to return the year in a new column in my dataframe titled 'Year'

My input:

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

Overall, I would like my output to look as follows

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

You are in the right direction, except that you don't need to loop:

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

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

Output:

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