PickleException:构造ClassDict(对于numpy.dtype)需要零个参数



我不明白如何解决这个问题,我已经讨论了这里的一些问题,但没有找到一个完全合适的答案。

我有一个数据框架,它有以下重要列:building_id、area、height。

我试图编写的UDF计算面积和高度的平方根之间的差值。它返回一个值,该值应添加到数据帧中。

def calculate_difference(area, height):
# calculate the square root of the area
import numpy as np
nr = np.sqrt(area)

# calculate the difference between the square root of the area and the height
dif = nr - height

return dif

然后我注册这个UDF:

calculate_differenceUDF = udf(calculate_difference)

当我传递两个数字时,函数就会工作,它会返回我期望的值。我想在我的数据帧中添加一个新列,在那里我们有一个基于函数的计算值。

display(df.withColumn("diff", calculate_differenceUDF(col("area"), col("height"))))

然后我收到这个错误:

PickleException:构造ClassDict需要零个参数(对于numpy.dtype(

我知道我可能没有返回正确的类型,但我不知道如何修复它!:(

我认为应该首先将numpy.sqrt()的返回值转换为python的float类型。

def calculate_difference(area, height):

nr = float(np.sqrt(area))
dif = nr - height
return dif

然后注册UDF

calculate_differenceUDF = udf(calculate_difference, FloatType())

确保返回适当的数据类型(在本例中为float(的其他正确答案。如果其他人仍然面临同样的错误,我还必须确保我的输入是适当的类型。例如:

def calculate_difference(area, height):
# specify input datatype
area = float(area)
height = float(height)
# calculate the square root of the area
import numpy as np
nr = np.sqrt(area)

# calculate the difference between the square root of the area and the height
dif = nr - height

return dif

最新更新