pandas关键字提取_将pandas列中的关键字与另一个元素列表匹配

I have a pandas dataframe as:

word_list

['nuclear','election','usa','baseball']

['football','united','thriller']

['marvels','hollywood','spiderman']

....................

....................

....................

I also have multiple number of lists with categories names,something as:-

movies=['spiderman','marvels','thriller']'

sports=['baseball','hockey','football'],

politics=['election','china','usa'] and many others categories.

All I want to match the keywords of pandas column word_list with my categories lists and assign the corresponding lists name in seperate column if keywords gets matched together and if any keywords not gets matched in any of the list then simply put as miscellaneous So, output I'm looking for as:-

word_list matched_list_names

['nuclear','election','usa','baseball'] politics,sports,miscellaneous

['football','united','thriller'] sports,movies,miscellaneous

['marvels','spiderman','hockey'] movies,sports

.................... .....................

.................... .....................

.................... ....................

I successfully get the match keywords as:-

for i in df['word_list']:

for j in movies:

if i in j:

print (i)

but this gives me the list of matched keywords. How I get the list names and add it into pandas column?

解决方案

You can flatten dictionary of lists first and then lookup by .get with miscellaneous for non matched values, then convert to sets for unique categories and convert to strings by join:

movies=['spiderman','marvels','thriller']

sports=['baseball','hockey','football']

politics=['election','china','usa']

d = {'movies':movies, 'sports':sports, 'politics':politics}

d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}

f = lambda x: ','.join(set([d1.get(y, 'miscellaneous') for y in x]))

df['matched_list_names'] = df['word_list'].apply(f)

print (df)

word_list matched_list_names

0 [nuclear, election, usa, baseball] politics,miscellaneous,sports

1 [football, united, thriller] miscellaneous,sports,movies

2 [marvels, hollywood, spiderman, budget] miscellaneous,movies

Similar solution with list comprehension:

df['matched_list_names'] = [','.join(set([d1.get(y, 'miscellaneous') for y in x]))

for x in df['word_list']]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值