pandas 在 Series 中查找共同的字符串并返回关键字 [英] pandas find strings in common among Series and return keywords
本文介绍了pandas 在 Series 中查找共同的字符串并返回关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想改进之前关于搜索字符串的问题在基于一系列关键字的熊猫系列中.我现在的问题是如何将在 DataFrame 行中找到的关键字作为新列.关键字系列w"是:
I would like to improve this previous question about searching strings in pandas Series based on a Series of keywords. My question now is how to get the keywords found in the DataFrame rows as a new column. The Keywords Series "w" is:
Skilful
Wilful
Somewhere
Thing
Strange
而数据帧df"是:
User_ID;Tweet
01;hi all
02;see you somewhere
03;So weird
04;hi all :-)
05;next big thing
06;how can i say no?
07;so strange
08;not at all
以下解决方案可以很好地屏蔽 DataFrame:
The following solution worked well for masking the DataFrame:
import re
r = re.compile(r'.*({}).*'.format('|'.join(w.values)), re.IGNORECASE)
masked = map(bool, map(r.match, df['Tweet']))
df['Tweet_masked'] = masked
并返回:
User_ID Tweet Tweet_masked
0 1 hi all False
1 2 see you somewhere True
2 3 So weird False
3 4 hi all :-) False
4 5 next big thing True
5 6 how can i say no? False
6 7 so strange True
7 8 not at all False
现在我正在寻找这样的结果:
Now I'm looking for a result like this:
User_ID;Tweet;Keyword
01;hi all;None
02;see you somewhere;somewhere
03;So weird;None
04;hi all :-);None
05;next big thing;thing
06;how can i say no?;None
07;so strange;strange
08;not at all;None
预先感谢您的支持.
推荐答案
如何更换
masked = map(bool, map(r.match, df['Tweet']))
与
masked = [m.group(1) if m else None for m in map(r.match, df['Tweet'])]
这篇关于pandas 在 Series 中查找共同的字符串并返回关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文