Spark 数据框不添加具有空值的列

问题描述 投票:0回答:3

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

原始数据框

╔══════╦══════╗
║ 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) 时,它不会添加具有空值的列。

我得到的输出是:

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

有没有办法将空值合并到计算中。任何帮助将不胜感激。

python apache-spark pyspark
3个回答
8
投票

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

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

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

4
投票

使用

null
函数将
0
替换为
coalesce
,然后将两列相加;使用
selectExpr
和 sql 语法:

df.selectExpr('*', 'coalesce(cola, 0) + coalesce(colb, 0) as colc')

0
投票

对于需要对列名列表执行此操作的人,以下代码应该有所帮助。 它将 cols_to_sum 列表中的所有列与 0 合并,然后对它们求和。

cols_to_sum = ['col1','col2','col3']

df.withColumn('sum', f.expr('+'.join('coalesce(' + col + ', 0)' for col in cols_to_sum)))
© www.soinside.com 2019 - 2024. All rights reserved.