使用 Pandas 进行部分字符串搜索的最佳解决方案

Best solution on partial string search with Pandas

我使用非常大的数据集 (1.5gb+) 并对其进行部分字符串搜索。

我可以为我的工作写一个脚本,但是时间太长了:

fhand = open('C:/Users/promotor/Documents/tce-sagres/TCE-PB-SAGRES-Empenhos_Esfera_Municipal.txt','r')
pergunta = raw_input('Pesquisa: ')
fresult = open('resultado.csv','w')
for line in fhand :
    #linha = linha + 0.001 
    #update_progress(int(linha)*1000)
    if pergunta in line : 
        print line
        fresult.write(line)  
print "terminado."""

我想知道在 Pandas 上是否有更快的方法来做到这一点。我试过 str.contains,但我只能搜索一个列。我想知道是否有更快的方法。我尝试了 "str.contains",但我只能搜索一列。

此致。

您正在迭代一个 for 循环,这可能会花费很多时间。我建议将整个文件作为字符串读取,然后使用正则表达式来匹配您的模式。

试试下面的代码,

import re
with open(your_file_name,'r') as f:
    lines=f.read()
name = input('pattern :')
pattern_to_match = r'(?<=\n).*%s.*(?=\n)'%name
matched_pattern = re.findall(pattern_to_match, lines, re.IGNORECASE)
print (matched_pattern)