【问题标题】:subtract two columns with null in spark dataframe在火花数据框中减去两列空值
【发布时间】:2017-09-21 02:55:14
【问题描述】:

我是 spark 新手,我有数据框 df:

+----------+------------+-----------+
| Column1  | Column2    | Sub       |                          
+----------+------------+-----------+
| 1        | 2          | 1         |                                         
+----------+------------+-----------+
| 4        | null       | null      |                          
+----------+------------+-----------+
| 5        | null       | null      |                          
+----------+------------+-----------+
| 6        | 8          | 2         |                          
+----------+------------+-----------+

当减去两列时,一列为空,因此结果列也为空。

df.withColumn("Sub", col(A)-col(B))

预期的输出应该是:

+----------+------------+-----------+
|  Column1 | Column2    | Sub       |                          
+----------+------------+-----------+
| 1        | 2          | 1         |                                           
+----------+------------+-----------+
| 4        | null       | 4         |                          
+----------+------------+-----------+
| 5        | null       | 5         |                          
+----------+------------+-----------+
| 6        | 8          | 2         |                          
+----------+------------+-----------+

我不想将 column2 替换为 0,它应该仅为 null。 有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    你可以使用when函数作为

    import org.apache.spark.sql.functions._
    df.withColumn("Sub", when(col("Column1").isNull, lit(0)).otherwise(col("Column1")) - when(col("Column2").isNull, lit(0)).otherwise(col("Column2")))
    

    你的最终结果应该是

    +-------+-------+----+
    |Column1|Column2| Sub|
    +-------+-------+----+
    |      1|      2|-1.0|
    |      4|   null| 4.0|
    |      5|   null| 5.0|
    |      6|      8|-2.0|
    +-------+-------+----+
    

    【讨论】:

      【解决方案2】:

      您可以在两列上将coalesce null 归零,然后进行减法:

      val df = Seq((Some(1), Some(2)), 
                   (Some(4), null), 
                   (Some(5), null), 
                   (Some(6), Some(8))
                  ).toDF("A", "B")
      
      df.withColumn("Sub", abs(coalesce($"A", lit(0)) - coalesce($"B", lit(0)))).show
      +---+----+---+
      |  A|   B|Sub|
      +---+----+---+
      |  1|   2|  1|
      |  4|null|  4|
      |  5|null|  5|
      |  6|   8|  2|
      +---+----+---+
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      相关资源
      最近更新 更多