我想弄清楚如何加快下面的正則運算式程序:
我有一些正則運算式模式字串,我利用這些聯合的正則運算式模式來標記 Pandas Dataframe 中的列。
因此,例如,一個合并的正則運算式字串將如下所示(如下);如果 Pandas 列中存在以下任何模式,請將該行標記為“自動”:
#example of unioned regex pattern string
auto_pattern = '''(
(ACURA)|
(ALFA ROMEO)|
(\bAUDI\b)|
(BMW\s?FINANCIAL)|
(FERRARI)|
(FIAT)|
(FORD MO?TO?R)|
((?=.*GMC?).*?(?=.*BUICK))|
(HONDA)|
(HYUNDAI)|
(INFINITI)|
(JAGUAR.*?(LAND))|
(JEEP(CHRYSL?E?R?)?)|
(\sKIA\s)|
(LEXUS)|
(MASERATI)|
(MAZDA)|
(MBFS.COM)|
(MERCEDES\S?(BENZ)?)|
(NISSAN)|
(PORSCHE)|
(ROLLS\s?ROYCE)|
(TESLA)|
(TOYOTA)|
(VCFS).*(LEASE)|
(VOLVO))(?!.*PAYROLL)
'''
下面的標簽函式將用于 DataFrame:
#function that applys patterns to dataframe
def labeler(text_string):
if re.search(typeone_pattern, text_string, flags=re.I) and not('Random Word Here') in text_string:
return 'Label 1'
if re.search(auto_pattern, text_string, flags=re.I | re.X):
return 'Label Auto'
if re.search(typetwo_pattern, text_string, flags=re.I):
return 'Label 2'
# a few more if re.search checks here......
return 'Other'
df['label'] = df['string_column'].apply(lambda x: labeler(x))
關于如何使這更有效/更快的任何想法?目前,對于 100 萬行,大約需要 1 分鐘。
我嘗試使用 Trie 資料結構,但這似乎只適用于單詞,而不適用于正則運算式模式。從我的研究來看,回圈正則運算式模式的最快方法似乎是將它們聯合起來,就像我上面在字串中所做的那樣。
也許我的貼標機功能可以更高效?或者我應該在 Pandas 中使用 .apply 以外的其他東西?沒有把握...
任何想法都非常感謝。
uj5u.com熱心網友回復:
至少,你可以預編譯你的正則運算式,而不是在每個回圈周期中編譯它們,這本質上是re.*頂級函式所做的。
首先,不是在變數中宣告模式字串,而是將模式字串編譯為正則運算式,然后在變數中:
#example of unioned regex pattern string
auto_pattern = re.compile('''(
(ACURA)|
...
(VOLVO))(?!.*PAYROLL)
''',
flags=re.I | re.X)
(并為其他變數做同樣的事情,typeone_pattern和typetwo_pattern。)
然后,re.search(<var>, 'text')您可以呼叫,而不是呼叫<var>.search('text'):
#function that applys patterns to dataframe
def labeler(text_string):
if typeone_pattern.search(text_string) and not 'Random Word Here' in text_string:
return 'Label 1'
if auto_pattern.search(text_string):
return 'Label Auto'
if typetwo_pattern.search(text_string):
return 'Label 2'
# a few more if re.search checks here......
return 'Other'
df['label'] = df['string_column'].apply(lambda x: labeler(x))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350817.html
下一篇:替換資料框列中空字典的值
