我想扩展问题 here
上述问题的解决方案返回 True 或 False。并且 bool 值可用于对正确的值进行子集化。
但是,我想获取匹配子字符串的搜索值。
例如,(借用上面的问题)
s = pd.Series(['cat','hat','dog','fog','pet'])
searchfor = ['og', 'at']
我想知道 'cat' 与 'at' 匹配,dog 与 'og' 匹配
最佳答案
IIUC,您希望这些值反射(reflect) 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
关于python - 用 pandas 搜索并返回匹配子串的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48614928/