【发布时间】:2022-07-06 15:03:32
【问题描述】:
我有问题。我想检查某个正则表达式是否出现在文本中(这个正则表达式稍后会变得更复杂。)。不幸的是,我的代码 sn-p 运行,但需要很长时间。如何重写代码以使其更快、更高效?
如果文本中存在该元素,则应找到相应元素的代码编号并将其写入新列。如果不存在,则应写入999
数据框
customerId text element code
0 1 Something with Cat cat 0
1 3 That is a huge dog dog 1
2 3 Hello agian mouse 2
代码sn-p
import pandas as pd
import copy
import re
d = {
"customerId": [1, 3, 3],
"text": ["Something with Cat", "That is a huge dog", "Hello agian"],
"element": ['cat', 'dog', 'mouse']
}
df = pd.DataFrame(data=d)
df['code'] = df['element'].astype('category').cat.codes
print(df)
def f(x):
match = 999
for element in df['element'].unique():
check = bool(re.search(element, x['text'], re.IGNORECASE))
if(check):
#print(forwarder)
match = df['code'].loc[df['element']== element].iloc[0]
break
x['test'] = match
return x
#print(match)
df['test'] = None
df = df.apply(lambda x: f(x), axis = 1)
预期输出
customerId text element code test
0 1 Something with Cat cat 0 0
1 3 That is a huge dog dog 1 1
2 3 Hello agian mouse 2 999
【问题讨论】:
-
所以你想要的只是,如果元素出现在文本 test=code 中,如果不是 text=999,对吧?
-
是的,你是对的。