【发布时间】:2020-05-22 03:05:01
【问题描述】:
我有一个下面的数据框 Df1 包含列“摘要”和“结束组”
Summary Closing Group
XX012 job abended with error Automation
XX015 job abended with error Automation
Front End issue TSL error Automation
XX015 job abended with error Automation
Front End issue TSL error Automation
Front End issue TSL error Automation
File not present error Automation
我在下面有另一个数据框Df2,带有“标签”列
Label
TSL error
job abended
File not present
如果Summary 中存在来自Label 的确切字符串,我想将每个Label 映射到Summary 列。
我使用for loop 编写了以下脚本来处理我的情况:
list_label= Df2['Label']
def is_phrase_in(phrase, text):
return re.search(r"\b{}\b".format(phrase), text, re.IGNORECASE) is not None
for idx2,row2 in Df1.iterrows():
for label in list_label:
print(label)
if is_phrase_in(label, row2['Summary']):
Df1.at[idx2,'Label'] =label
break
上面的代码给了我预期的结果,但是在7000 label list 和20000 Summary 上运行时需要很长时间。
为了优化这一点,我使用了Lambda 函数,如下所示:
Df1['Label'] = Df1['Summary'].apply(lambda x : next((l for l in list_label['Label'] if is_phrase_in(l,x)), 'No Label Found'))
但是这个脚本需要更多时间,甚至比 for loop 还要多。
谁能告诉我我在这里做错了什么,或者有没有其他方法可以优化这段代码。
我的预期输出:
Summary Closing Group Label
XX012 job abended with error Automation job abended
XX015 job abended with error Automation job abended
Front End issue TSL error Automation TSL error
Server down error Server No Label found
XX015 job abended with error Automation job abended
Front End issue TSL error Automation TSL error
Front End issue TSL error Automation TSL error
File not present error Automation File not present
【问题讨论】:
-
您实际上可以尝试 numpy 或 panda。它们自然更快,因为它们为数据帧优化了引擎。像这样:stackoverflow.com/questions/41588034/…
-
您真的有 7,000 个唯一的、可能有效的标签,仅用于 20,000 个数据点吗?必须为每个数据点搜索众多标签中的每一个标签会大大扩展时间要求 - 如果您可以优化标签列表(如果没有上下文则很难理解),那么这可能会非常有益
-
是的,我有大约 7000 个独特的标签。
-
我可以建议这很容易并行化吗?
-
@brunodesthuilliers - 你的意思是多线程吗?如果没有,那么您可以分享可并行化的链接
标签: python python-3.x