我将尝试通过在数据框中添加两个现有列来创建一个新列。
原始数据框
╔══════╦══════╗
║ 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 ║
╚══════╩══════╩══════╝
有没有办法将空值纳入计算中。任何帮助都将不胜感激。
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