使用pandas搜索并返回匹配子字符串的索引

时间:2018-02-05 02:01:30

标签: python string pandas series

我想扩展问题here

上述问题中的解决方案返回True或False。并且布尔值可用于对正确的值进行子集化。

但是,我想获得与子字符串匹配的搜索值。

例如,(借鉴上述问题)

s = pd.Series(['cat','hat','dog','fog','pet'])
searchfor = ['og', 'at']

我想知道'cat'与'at'匹配,而dog匹配'og'

2 个答案:

答案 0 :(得分:4)

IIUC,您希望这些值反映searchfor列表中与您的单词匹配的项目的索引。您可以先修改searchfor对象 -

m = {'^.*{}.*$'.format(s) : str(i) for i, s in enumerate(searchfor)}

这是<pattern : index>映射的字典。现在,使用pd.Series.replace -

致电regex=True
s = s.replace(m, regex=True)
s[:] = np.where(s.str.isdigit(), pd.to_numeric(s, errors='coerce'), -1)

s

0    1
1    1
2    0
3    0
4   -1
dtype: int64

如果您想按模式列出匹配值列表,则需要str.extract + groupby + apply -

p = '(^.*({}).*$)'.format('|'.join(searchfor))

s.str.extract(p, expand=True)\
 .groupby([1])[0]\
 .apply(list)

1
at    [cat, hat]
og    [dog, fog]
Name: 0, dtype: object

答案 1 :(得分:2)

这是使用defaultdict + replace,最后我做了..

d=dict(zip(searchfor,[""]*2))

s1=s.replace(d,regex=True)
import collections
d = collections.defaultdict(dict)
for x,y in zip(s1.index,s1):
    d[x][y]=''

s.to_frame('a').T.replace(dict(d), regex=True).T.a


Out[765]: 
0    at
1    at
2    og
3    og
4      
Name: a, dtype: object