Spark dataframe无法添加空值列

4

我将尝试通过在数据框中添加两个现有列来创建一个新列。

原始数据框

╔══════╦══════╗
║ cola ║ colb ║
╠══════╬══════╣
║ 1    ║ 1    ║
║ null ║ 3    ║
║ 2    ║ null ║
║ 4    ║ 2    ║
╚══════╩══════╝

预期输出与派生列
╔══════╦══════╦══════╗
║ cola ║ colb ║ colc ║
╠══════╬══════╬══════╣
║ 112 ║
║ null ║ 33 ║
║ 2    ║ null ║    2 ║
║ 426 ║
╚══════╩══════╩══════╝

当我使用df = df.withColumn('colc',df.cola+df.colb)时,它不会添加包含空值的列。
我得到的输出是:
╔══════╦══════╦══════╗
║ cola ║ colb ║ colc ║
╠══════╬══════╬══════╣
║ 112    ║
║ null ║ 3    ║ null ║
║ 2    ║ null ║ null ║
║ 426    ║
╚══════╩══════╩══════╝

有没有办法将空值纳入计算中。任何帮助都将不胜感激。

2个回答

7
你可以将 coalesce 使用为0来获得一个总和。对于两列都为空的情况,你可以使用条件函数。对于你的情况,代码应该类似于:
df.selectExpr('*', 'if(isnull(cola) and isnull(colb), null, coalesce(cola, 0) + coalesce(colb, 0)) as colc')

4
coalesce函数将null替换为0,然后将两列相加;使用selectExpr和SQL语法:
df.selectExpr('*', 'coalesce(cola, 0) + coalesce(colb, 0) as colc')

当将两个null相加时,这会产生一个输出为0的结果,例如:null+null=0。有没有办法使输出结果为null呢?例如:null+null=null。 - Mr.P
使用 case when 添加条件:df.selectExpr('*', 'case when cola is null and colb is null then null else coalesce(cola, 0) + coalesce(colb, 0) end as colc') - Psidom
1
我有一个列列表并想执行相同的操作。如何做到这一点? - Mukul Aggarwal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接