首页 > 解决方案 > lambda函数中的Pyspark udf函数错误

问题描述

我在下面写了一个 udf 函数,它给我一个错误。请帮忙。

下面是我的数据集;

df1 = sqlContext.range(0, 1000)\
 .withColumn('normal1',func.abs(10*func.round(randn(seed=1),2)))\
 .withColumn('normal2',func.abs(100*func.round(randn(seed=2),2)))\
 .withColumn('normal3',func.abs(func.round(randn(seed=3),2)))

df1 = df1.withColumn('Y',when(df1.normal1*df1.normal2*df1.normal3>750, 1)\
       .otherwise(0))

udf函数如下:

from pyspark.sql import types as T
balancingRatio=0.8
calculateWeights = udf(lambda d:(1 * balancingRatio) if d==0 else (1 * (1.0 -   balancingRatio)),T.IntegerType())
weightedDataset = df1.withColumn('classWeightCol', calculateWeights('Y'))
weightedDataset.show() 

这需要一些时间并给我一个错误;

Py4JJavaError: An error occurred while calling o670.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 
in stage 25.0 failed 1 times, most recent failure: Lost task 0.0 in stage 
25.0 (TID 427, localhost, executor driver): org.apache.spark.SparkException: 
Python worker failed to connect back.

可能是什么问题?谢谢你。

我发现互联网上的一个简单示例也不起作用

maturity_udf = udf(lambda age: "adult" if age >=18 else "child", 
 T.StringType())
df = sqlContext.createDataFrame([{'name': 'Alice', 'age': 1}])
df.withColumn("maturity", maturity_udf(df.age)).show()

不是:我得到了 python 3.7.1 和 spark 2.4

标签: lambdaerror-handlingpysparkuser-defined-functions

解决方案


您需要通过将OBJC_DISABLE_INITIALIZE_FORK_SAFETY变量设置为来禁用分叉安全,YES这为我解决了这个问题。

import os
os.environ['OBJC_DISABLE_INITIALIZE_FORK_SAFETY'] = 'YES'

推荐阅读