我有以下格式的数据框 -
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
但是,我得到以下输出 - 其中空整数和长整数之和为空
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)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)