apache-spark - 在大数据上优化 Pyspark UDF
问题描述
我正在尝试优化此代码,当列的值(pyspark 数据框的)在 [类别] 中时,它会创建一个虚拟对象。
当运行在 100K 行时,运行大约需要 30 秒。就我而言,我有大约 20M 行,这将花费很多时间。
def create_dummy(dframe,col_name,top_name,categories,**options):
lst_tmp_col = []
if 'lst_tmp_col' in options:
lst_tmp_col = options["lst_tmp_col"]
udf = UserDefinedFunction(lambda x: 1 if x in categories else 0, IntegerType())
dframe = dframe.withColumn(str(top_name), udf(col(col_name))).cache()
dframe = dframe.select(lst_tmp_col+ [str(top_name)])
return dframe
换句话说,我如何优化这个功能并减少我的数据量的总时间?以及如何确保此函数不会迭代我的数据?
感谢您的建议。谢谢
解决方案
您不需要 UDF 来对类别进行编码。您可以使用isin
:
import pyspark.sql.functions as F
def create_dummy(dframe, col_name, top_name, categories, **options):
lst_tmp_col = []
if 'lst_tmp_col' in options:
lst_tmp_col = options["lst_tmp_col"]
dframe = dframe.withColumn(str(top_name), F.col(col_name).isin(categories).cast("int")).cache()
dframe = dframe.select(lst_tmp_col + [str(top_name)])
return dframe
推荐阅读
- mongodb - 在 pymongo 中触发
- c# - 如何在 WASM 运行时中运行 UnitTest
- laravel - 存储多态 belongsTo 关系的最佳实践
- r - 删除数据框中包含特定值的因子列
- firebase - > 任务:react-native-async-storage_async-storage:parseDebugLocalResources FAILED
- windows - 我想要一个批处理文件来删除绝对路径位置 (F:\work) 中的所有文件,但名为“txt1.txt”和“txt2.txt”的两个文件除外
- python - 如何在 MongoDB 保存中更改对象的行为?
- opengl - 为什么我在多边形之间有这种奇怪的接缝?
- angular - Angular 升级并添加模块联合插件后,浏览器未加载应用程序
- css - 将溢出装入父容器