Spark 数据框不添加具有空值的列 [英] Spark dataframe not adding columns with null values

查看:38
本文介绍了Spark 数据框不添加具有空值的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a new column by adding two existing columns in my dataframe.

原始数据框

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

派生列的预期输出

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

当我使用 df = df.withColumn('colc',df.cola+df.colb) 时,它不会添加具有空值的列.

When I use df = df.withColumn('colc',df.cola+df.colb), it doesn't add columns with null values.

我得到的输出是:

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

有什么方法可以将空值合并到计算中.任何帮助将不胜感激.

Is there any way to incorporate the null values into the calculation. Any help would be appreciated.

推荐答案

您可以合并到 0 以获得总和.对于两列都为空的情况,您可以使用条件函数.

You can coalesce to 0 to get a sum. For cases where both columns are null, you can make use of conditional functions.

对于您的情况,代码应该类似于

For your case, the code should look something like

df.selectExpr('*', 'if(isnull(cola) and isnull(colb), null, coalesce(cola, 0) + coalesce(colb, 0)) as colc')

这篇关于Spark 数据框不添加具有空值的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆