keywords matching of list elements with pandas column

Viewed 1130

I have list of elements as:

 A=  ['loans','s-class','veyron','trump','rihana','drake','election']

I also have another pandas dataframe B with columns category and words which is comma seperated string as:-

category              words
audi                  a4, a6
bugatti               veyron, chiron
mercedez              s-class, e-class
dslr                  canon, nikon
apple                 iphone,macbook,ipod
finance               sales,loans,sales price
politics              trump, election, votes
entertainment         spiderman,thor, ironmen
music                 beiber, rihana,drake
........              ..............
.........             .........

All I want to map elements of list A with column words and assign corresponding category into a new list.So, expected output would be.

matched_categories=['finance','mercedez','bugatti','politics','music','music','politics']
1 Answers

Filter by boolean indexing with iat for select first matched value:

#if always matched all values
matched_categories = [df.loc[df['words'].str.contains(x), 'category'].iat[0] for x in A]
print (matched_categories)
['finance', 'mercedez', 'bugatti', 'politics', 'music', 'music', 'politics']

More general solution if some value is not matched - then return not matched value:

#added last aaa value
A = ['loans','s-class','veyron','trump','rihana','drake','election','aaa']

matched_categories = [next(iter(df.loc[df['words'].str.contains(x),'category']),'not matched')
                      for x in A]
print (matched_categories)
['finance', 'mercedez', 'bugatti', 'politics', 'music', 'music', 'politics', 'not matched']
Related