python - 在 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 的最佳方法是什么?
解决方案
首先,你的代码pandas
可以直接在databricks上运行,无需任何其他操作,如下图。
然后,我看到你想在做同样的事情时获得更好的性能,所以我认为你可以尝试使用koalas
PySpark 的包来获得类似的 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了解。
推荐阅读
- angular - 在 Angular 中初始化之前无法访问模块
- python - 如何在 websockets 中使用多线程?
- nginx - Nginx 重写文件下载
- javascript - 数据表添加下拉列表列
- python - matplotlib.pyplot set_xticks 和 set_xticklabels 问题
- swift - 仅在 iPhone 7 真实设备中的 URL 无效
- android - Android Grid 布局未按预期工作
- xml - .net core 5 不绑定 XML 模型
- identity - ms-identity-python-flask-webapp-call-graph - identity_context_data 中的各种属性或方法是什么
- python - 如何创建包含所有可能组合和聚合结果的两列的 groupby