调用返回FloatType()的UDF时,“构造ClassDict的预期零参数(对于numpy.dtype)”

时间:2018-12-16 06:52:27

标签: python dataframe pyspark pyspark-sql

我认为这与以下内容有关:Spark Error:expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct)

我有一个数据框

id col_1 col_2
1 [1,2] [1,3]
2 [2,1] [3,4]

我想创建另一列,该列是cosinecol_1之间的col_2距离。

from scipy.spatial.distance import cosine

def cosine_distance(a,b):
    try:
        return cosine(a, b)
    except Exception as e:
        return 0.0 # in case division by zero

然后我定义了一个udf

cosine_distance_udf = udf (cosine_distance, FloatType())

最后:

new_df = df.withColumn('cosine_distance', cosine_distance_udf('col_1', 'col_2'))

我有一个错误:PickleException: expected zero arguments for construction of ClassDict (for numpy.dtype)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

检查cosine的返回类型时,错误的原因很明显:

type(cosine([1, 2], [1, 3]))
# numpy.float64

但是,np.float64float的子类:

issubclass(np.float64, float)
# True

因此,只需稍作更改,您的功能

def cosine_distance(a, b):
    try:
        return float(cosine(a, b)) # cosine(a, b).item()
    except Exception as e:
        return 0.0 # in case division by zero

这将起作用

df.withColumn('cosine_distance', cosine_distance_udf('col_1', 'col_2')).show()

+------+------+---------------+
| col_1| col_2|cosine_distance|
+------+------+---------------+
|[1, 2]|[3, 4]|     0.01613009|
|[2, 1]|[3, 4]|     0.10557281|
+------+------+---------------+