在Pyspark中顺序应用多个正则表达式进行文本清理的最快方法

时间:2019-11-02 22:17:51

标签: python regex apache-spark databricks

我有一列希望使用大量我想顺序应用的正则表达式清除。

即使是大熊猫,这也是一个耗时的过程,但至少我可以通过将其作为函数来使用。

作为一个具体示例:

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的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

首先,带有pandas的代码可以直接在数据块上运行,而无需任何其他操作,如下图所示。

enter image description here

然后,我看到您希望通过执行相同的操作而获得更好的性能,因此,我认为您可以尝试对PySpark使用koalas软件包来获得类似pandas的UX。要在数据砖集群中安装koalas软件包非常容易,只需按照下图进行安装即可。

enter image description here

注意:koalas软件包的最新版本需要spark-2.4.4,因此,必须如下图所示选择Spark 2.4.4版本来创建集群。

enter image description here

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

enter image description here

不用担心调用不赞成使用的函数的用户警告信息,您可以参考SO线程UserWarning: pyarrow.open_stream is deprecated, please use pyarrow.ipc.open_stream warnings来了解它。