您可以使用 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>"))