Spark:将数据框中的空值替换为列的平均值

时间:2016-07-13 15:54:54

标签: java sql scala apache-spark

如何创建UDF以使用列平均值以编程方式替换每列中spark数据帧中的空值。例如,在示例数据中,col1 null值的值为((2 + 4 + 6 + 8 + 5)/ 5)= 5.

示例数据:

col1    col2    col3
2       null    3
4       3       3
6       5       null
8       null    2
null    6       4
5       2       8

所需数据:

col1    col2    col3
2       4       3
4       3       3
6       5       4
8       4       2
5       6       4
5       2       8

1 个答案:

答案 0 :(得分:4)

一般来说,这里不需要UDF。所有你真的是聚合表:

val df = Seq(
  (Some(2), None, Some(3)), (Some(4), Some(3), Some(3)),
  (Some(6), Some(5), None), (Some(8), None, Some(2)),
  (None, Some(6), Some(4)), (Some(5), Some(2), Some(8))
).toDF("col1", "col2", "col3").alias("df")

val means = df.agg(df.columns.map(c => (c -> "avg")).toMap)

并使用coalesce广播笛卡尔:

val exprs = df.columns.map(c => coalesce(col(c), col(s"avg($c)")).alias(c))

df.join(broadcast(means)).select(exprs: _*)