首页 > 解决方案 > 在 Pyspark 中按顺序应用多个正则表达式进行文本清理的最快方法

问题描述

我有一个列,我希望使用大量要按顺序应用的正则表达式来清理它。

即使是熊猫,这也是一个耗时的过程,但至少我可以通过将它作为一个函数应用来摆脱困境。

作为一个具体的例子:

import pandas as pd
import re


regex_tuples_list = [(r'\bMR\b', 'middle right', re.I), 
                     ('\bmiddle right area\b', 'center', re.I),
                    ]

def apply_regex(text):
    for (to_repl, value, re_flags) in regex_tuples_list:
        to_repl_compiled = re.compile(to_repl, re_flags)
        text = re.sub(to_repl_compiled, value, text)
    return text

s = pd.Series(['Install the part in the MR', 
               'Check the MR area before using the tool', 
               'Always begin from the middle right area',
              ])

print(s.apply(apply_regex))

## Prints...
#      Install the part in the middle right
#    Check the center before using the tool
#              Always begin from the center

使用 Pyspark 的最佳方法是什么?

标签: pythonregexapache-sparkdatabricks

解决方案


首先,你的代码pandas可以直接在databricks上运行,无需任何其他操作,如下图。

在此处输入图像描述

然后,我看到你想在做同样的事情时获得更好的性能,所以我认为你可以尝试使用koalasPySpark 的包来获得类似的 UX,例如pandas. 而且在databricks集群中安装koalas包非常简单,按照下图安装即可。

在此处输入图像描述

注意:最新版本的koalas包需要spark-2.4.4,所以创建集群时必须选择Spark2.4.4版本,如下图。

在此处输入图像描述

最后,您只需要使用PySpark 来运行相同的代码,而不需要任何更多import databricks.koalas as ks的代码更改,以获得更好的性能,如下图所示。import pandas as pd

在此处输入图像描述

调用 deprecated 函数时不用担心用户警告信息,可以参考 SO 线程UserWarning: pyarrow.open_stream is deprecated,请使用 pyarrow.ipc.open_stream warnings了解。


推荐阅读