Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:加速许多字符串搜索_Python_Pandas - Fatal编程技术网

Python 熊猫:加速许多字符串搜索

Python 熊猫:加速许多字符串搜索,python,pandas,Python,Pandas,我有一个系列,其中每个元素都是一个空列表: matches = pd.Series([[]]*4) 和另一系列字符串: strs = pd.Series(["word3, xx word1 word1", "yy", "word2. o", "awldkj"]) 我想用一组关键字中不区分大小写的关键字匹配填充cats: terms = ["word1", "Word2", "worD3"] 目前,我逐一遍历每个搜索词 for tcat in tcats: tcat_

我有一个系列,其中每个元素都是一个空列表:

matches = pd.Series([[]]*4)
和另一系列字符串:

strs = pd.Series(["word3, xx word1 word1", "yy", "word2. o", "awldkj"])
我想用一组关键字中不区分大小写的关键字匹配填充
cats

terms = ["word1", "Word2", "worD3"]
目前,我逐一遍历每个搜索词

    for tcat in tcats:
        tcat_re = rf'\b{tcat}\b'
        has_cat = strs.str.contains(tcat_re, case=False)
        print(has_cat.sum(), "matches for", tcat)
        w_cats = has_cat.map({True: [tcat], False: []})
        cats = cats.combine(w_cats, lambda li, li2: li + li2)
从而得出正确的解决方案:

1 matches for word1
1 matches for Word2
1 matches for worD3

In [507]: matches
Out[509]: 
0    [word1, worD3]
1                []
2           [Word2]
3                []
需要注意的两个方面:

  • 中匹配项的顺序匹配
    并不重要
  • word1
    在strs.iloc[0]中出现两次,但只产生一个匹配项。如果生成了两个匹配项就可以了,因为列表可以映射到一个集合,然后再映射回列表
但是速度太慢了,因为我真正的单词
terms
列表和
strs
系列要大得多。有什么方法可以加快速度吗?

您可以尝试:

strs.str.findall('(?i){}'.format('|'.join([rf'\b{i}\b' for i in terms]))).map(set)

0    {word1, word3}
1                {}
2           {word2}
3                {}
或为维持秩序:

(strs.str.findall('(?i){}'.format('|'.join([rf'\b{i}\b' for i in terms])))
                               .map(lambda x: [*dict.fromkeys(x).keys()]))

0    [word3, word1]
1                []
2           [word2]
3                []

你能试试strs.str.findall('(?i){}.format('|'.join([rf'\b{i}\b'表示i的术语))).map(set)?@anky似乎能用吗?这个解决方案是否等效,但更干净一点
strs.str.findall('|'.join([rf'\b{i}\b'代表i术语]),flags=re.IGNORECASE).map(set)
您的注释中的内容与我的注释相同,除了
(?i)
这是IGNORECASE,您还需要使用
rf'\b{re.escape(}i)\b'
允许使用任意术语