Keywords Matching Of List Elements With Pandas Column
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 c
Solution 1:
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']
Post a Comment for "Keywords Matching Of List Elements With Pandas Column"