在Spark SQL中,`coalesce()`函数用于从给定列中选择非空值。它接受一个或多个列作为参数,并返回第一个非空值。在数据清洗和预处理过程中,
`coalesce()`函数非常有用,特别是在处理缺失值或空值时。
以下是使用`coalesce()`函数进行指定列填充数据的示例:
假设我们有一个名为`employees`的DataFrame,其中包含以下列:`name`, `age`, `address`和`salary`。某些行中的`age`列可能包含空值(`null`)。
val employees = spark.createDataFrame(Seq(
("John", 30, "New York", 5000),
("Mary", null, "London", 6000),
("Bob", 40, "Paris", 7000),
("Alice", null, "Tokyo", 8000)
)).toDF("name", "age", "address", "salary")
我们可以使用`coalesce()`函数来填充`age`列中的空值。在这个例子中,我们将使用`coalesce(age, 0)`来将空值替换为0。
val filledEmployees = employees.withColumn("age", coalesce($"age", lit(0)))
filledEmployees.show()
输出结果:
```diff
+------+------+---------+------+
| name| age| address|salary|
+------+------+---------+------+
| John| 30| New York| 5000|
| Mary|null | London| 6000|
| Bob| 40| Paris | 7000|
|Alice|null | Tokyo | 8000|
+------+------+---------+------+
```
在填充后的DataFrame中,空值被替换为0。请注意,`coalesce()`函数可以接受多个参数,因此您可以使用它来从多个列中选择非空值。