DataFrame 列(数组类型)包含 Null 值和空数组 (len =0)。如何将 Null 转换为空数组?

DataFrame column (Array type) contains Null values and empty array (len =0). How to convert Null to empty array?

我有一个带有数组列 (StringType) 的 Spark DataFrame

示例数据帧:

df = spark.createDataFrame([
  [None],   
  [[]],   
  [['foo']] 
]).toDF("a")

当前输出:

+-----+
|    a|
+-----+
| null|
|   []|
|[foo]|
+-----+

期望输出:

+-----+
|    a|
+-----+
|   []|
|   []|
|[foo]|
+-----+

我需要将 Null 值转换为空数组以与另一个数组列连接。

已经试过了,但是不行

df.withColumn("a",F.coalesce(F.col("a"),F.from_json(F.lit("[]"), T.ArrayType(T.StringType()))))

使用array函数。

df = spark.createDataFrame([
  [None],   
  [[]],   
  [['foo']] 
]).toDF("a")

import pyspark.sql.functions as F

df.withColumn('a', F.coalesce(F.col('a'), F.array(F.lit(None)))).show(10, False)
+-----+
|a    |
+-----+
|[]   |
|[]   |
|[foo]|
+-----+

结果现在是array(string),所以没有空值。请检查结果。

temp = spark.sql("SELECT a FROM table WHERE a is NULL")
temp.show(10, False)
temp = spark.sql("SELECT a FROM table WHERE a = array(NULL)")
temp.show(10, False)
temp = spark.sql("SELECT a FROM table")
temp.show(10, False)


+---+
|a  |
+---+
+---+

+---+
|a  |
+---+
|[] |
+---+

+-----+
|a    |
+-----+
|[]   |
|[]   |
|[foo]|
+-----+