如何在Spark/PySpark中对数据帧中包含空值的两列求和



我有一个以下格式的数据帧-

Col1    |cnt_Test1     |cnt_Test2
_______________________________________
Stud1   | null        | 2
Stud2   | 3           | 4
Stud3   | 1           | null

我想通过聚合cnt_Test1和cnt_Test2来创建一个新列,以获得以下结果-

Col1    |cnt_Test1     |cnt_Test2     | new_Count
____________________________________________________
Stud1   | null        | 2              | 2
Stud2   | 3           | 4              | 7
Stud3   | 1           | null           | 1

然而,我得到了以下输出-其中null和长整数之和为null

Col1    |cnt_Test1     |cnt_Test2     | new_Count
____________________________________________________
Stud1   | null        | 2              | null
Stud2   | 3           | 4              | 7
Stud3   | 1           | null           | null

您需要使用类似以下的coalesce函数

df = spark.createDataFrame(
[
("Stud1",None,2),
("Stud1",3,4),
("Stud1",1, None)], 
("col1","cnt_Test1", "cnt_Test2"))

# Import functions
import pyspark.sql.functions as f
df1 = df.withColumn("new_count", f.coalesce(f.col('cnt_Test1'), f.lit(0)) + f.coalesce(f.col('cnt_Test2'), f.lit(0)))

您也可以分两步完成:

df2 = df.na.fill(0)
df2.withColumn("new_Count", df2["cnt_Test1"] + df2["cnt_Test2"]).show()

最新更新