pandas - 使用 ArrayType 列将 UDF 重写为 pandas udf

标签 pandas apache-spark pyspark user-defined-functions

我正在尝试将 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 为您的项目工作,需要三个方面:

1。 pandas UDF,或更准确地说,Apache Arrow 不像常见的 udf 那样支持复杂类型。(从 pyspark 3.0.1pyarrow 2.0.0 开始)

例如:

2。如果您运行的是 Java 11,这是 (py)Spark 3 中的默认设置。您需要添加以下内容作为 Spark 配置的一部分:

spark.driver.extraJavaOptions='-Dio.netty.tryReflectionSetAccessible=true'
spark.executor.extraJavaOptions='-Dio.netty.tryReflectionSetAccessible=true'

这将解决上面提到的java.lang.UnsupportedOperationException

3。确保您的虚拟环境 python 路径已添加到您的 pyspark_python

environ['PYSPARK_PYTHON']='./your/virtual/enviroment/path'

关于pandas - 使用 ArrayType 列将 UDF 重写为 pandas udf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64960642/

相关文章:

python - 在多索引 DF 中按索引值选择

apache-spark - SPARK中提供了HIVE表,但未在Hive CLI中显示

dataframe - Pyspark 数据帧比较

python - 值错误 : too many values to unpack (while reducing with foldByKey)

azure - 在 Azure Databricks 中反序列化事件中心消息

python - 构建 datetime64 和 pandas 时间序列的有效方法?

python - 分解趋势、季节和残差时间序列元素

python - 在绘制 Pandas 之前过滤数据

python-3.x - Pyspark Column.isin() 用于大集合

python - PySpark 和广播连接示例