Spark DataFrame 中将 null 值转换为空数组

2024-03-13

我有一个 Spark 数据框,其中一列是整数数组。该列可以为空,因为它来自左外连接。我想将所有空值转换为空数组,这样以后就不必处理空值了。

我想我可以这样做:

val myCol = df("myCol")
df.withColumn( "myCol", when(myCol.isNull, Array[Int]()).otherwise(myCol) )

但是,这会导致以下异常:

java.lang.RuntimeException: Unsupported literal type class [I [I@5ed25612
at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:49)
at org.apache.spark.sql.functions$.lit(functions.scala:89)
at org.apache.spark.sql.functions$.when(functions.scala:778)

显然数组类型不受支持when功能。还有其他简单的方法来转换空值吗?

如果相关的话,这里是该列的架构:

|-- myCol: array (nullable = true)
|    |-- element: integer (containsNull = false)

您可以使用 UDF:

import org.apache.spark.sql.functions.udf

val array_ = udf(() => Array.empty[Int])

结合WHEN or COALESCE:

df.withColumn("myCol", when(myCol.isNull, array_()).otherwise(myCol))
df.withColumn("myCol", coalesce(myCol, array_())).show

In the 最新版本您可以使用array功能:

import org.apache.spark.sql.functions.{array, lit}

df.withColumn("myCol", when(myCol.isNull, array().cast("array<integer>")).otherwise(myCol))
df.withColumn("myCol", coalesce(myCol, array().cast("array<integer>"))).show

请注意,只有从以下位置转换时,它才会起作用string允许更改为所需的类型。

当然,同样的事情也可以在 PySpark 中完成。对于遗留解决方案,您可以定义udf

from pyspark.sql.functions import udf
from pyspark.sql.types import ArrayType, IntegerType

def empty_array(t):
    return udf(lambda: [], ArrayType(t()))()

coalesce(myCol, empty_array(IntegerType()))

在最近的版本中只需使用array:

from pyspark.sql.functions import array

coalesce(myCol, array().cast("array<integer>"))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spark DataFrame 中将 null 值转换为空数组 的相关文章

随机推荐