Creating a column based on matches from a list

Viewed 251

I have a data frame with a column of job titles and the company name in the same string of each row, I also have a list of all possible company names.

How do I search the column of my data frame to see if it contains one of the companies in my list and then create a new column with just the company names if there is a match in some rows? Attached two photos.

enter image description here

enter image description here

I tried a few solutions but can't find one that works.

The original logic I followed is; df['Company'] = df['Title'].str.contains(x for x in joblist) but obviously that throws an error.

Any help is appreciated, thanks.

2 Answers

Use Series.str.contains with joined values by | for regex or for test values:

df['test'] = df['Title'].str.contains('|'.join(joblist))

and if want extract values by list use Series.str.extract:

df['Company'] = df['Title'].str.extract(f'({"|".join(joblist)})', expand=False)

You need to access all the items in the list with companies and compare them with each value of column "Title". You can check if a String contains another String using operator in.

all_titles = df['Title']
for x in all_titles:
    for y in df:
        if (y in x ):
            //your code here
Related