【问题标题】:Search and return index of matching substring with pandas用 pandas 搜索并返回匹配子串的索引
【发布时间】:2019-01-13 14:36:26
【问题描述】:

我想扩展here提出的问题

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

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

例如,(借用上面的问题)

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

我想知道 'cat' 匹配 'at' 和 dog 匹配 'og'

【问题讨论】:

  • 也欢迎您为您选择的答案投票。谢谢(-:

标签: python string pandas series


【解决方案1】:

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

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

这是<pattern : index> 映射的字典。现在,用regex=True 拨打pd.Series.replace -

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

【讨论】:

  • 谢谢。那行得通。但是,我意识到我真正想要的是将所有匹配的字符串作为逗号分隔值返回。我会问另一个问题。
  • @SharvariGc 不,不用担心。我会编辑我的答案。编辑:完成,查看我的最新编辑。
  • 谢谢。我如何为系列的第一个元素获得 ['og,at'],s = pandas.Series(['cat dog','hat cat','dog','fog cat','pet'])搜索时 searchfor = ['og', 'at']
  • 在 np.where 之外真的很难想 :-)
  • @SharvariGc 啊...这很难。可以再开个q吗?
【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多