python - 用 pandas 搜索并返回匹配子串的索引

标签 python string pandas series

我想扩展问题 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.replaceregex=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/

相关文章:

string - 将字符串转换为字母数字

Python:如何将列表/数组/pd.Series中的零值设置为下一个非零值?

Python - Pandas 索引和选择

python - 在 Pandas 中将索引连接到多重索引

python - 矩阵程序,使用python中的绑定(bind)来停止/启动

c# - 使用超出范围的子字符串拆分字符串

c - 字符串到空格分隔的整数

python - 计算一系列值变化的次数

python - PyQt 中的悬停问题

python:根据单个列表中的元素制作嵌套列表