我正在尝试将UDF重写为 pandas UDF。
但是,当涉及到带有ArrayType的列时。我正在努力寻找正确的解决方案。
我有一个数据框,如下所示:
+-----------+--------------------+
| genre| ids|
+-----------+--------------------+
| Crime|[6, 22, 42, 47, 5...|
| Romance|[3, 7, 11, 15, 17...|
| Thriller|[6, 10, 16, 18, 2...|
| Adventure|[2, 8, 10, 15, 29...|
| Children|[1, 2, 8, 13, 34,...|
| Drama|[4, 11, 14, 16, 1...|
| War|[41, 110, 151, 15...|
|Documentary|[37, 77, 99, 108,...|
| Fantasy|[2, 56, 60, 126, ...|
| Mystery|[59, 113, 123, 16...|
+-----------+--------------------+
以下UDF效果很好:
pairs_udf = udf(lambda x: itertools.combinations(x, 2), transformer.schema)
df = df.select("genre", pairs_udf("ids").alias("ids"))
输出如下:
+-----------+--------------------+
| genre| ids|
+-----------+--------------------+
| Crime|[[6, 22], [6, 42]...|
| Romance|[[3, 7], [3, 11],...|
| Thriller|[[6, 10], [6, 16]...|
| Adventure|[[2, 8], [2, 10],...|
| Children|[[1, 2], [1, 8], ...|
| Drama|[[4, 11], [4, 14]...|
| War|[[41, 110], [41, ...|
|Documentary|[[37, 77], [37, 9...|
| Fantasy|[[2, 56], [2, 60]...|
| Mystery|[[59, 113], [59, ...|
+-----------+--------------------+
但是,用中编写函数等效pandas udf
。
PS:我了解,或者,我可以使用交叉联接来达到相同的结果。
但是,我对Pandas udf如何使用ArrayType处理列感到更加好奇。
我将在这里分享我的发现:
为了使Pandas udf在你的项目中发挥作用,有3个方面:
pyspark 3.0.1
,pyarrow 2.0.0
)例如:
ArrayType(StringType())
由pandas udf支持。ArrayType(SturctType([...]))
不支持。你可以查看更多信息:https : //spark.apache.org/docs/latest/sql-pyspark-pandas-with-arrow.html#supported-sql-typesspark.driver.extraJavaOptions='-Dio.netty.tryReflectionSetAccessible=true'
spark.executor.extraJavaOptions='-Dio.netty.tryReflectionSetAccessible=true'
这将解决java.lang.UnsupportedOperationException
上述问题。
pyspark_python
IE
environ['PYSPARK_PYTHON']='./your/virutal/enviroment/path'