首页 > 解决方案 > 如何使用列值执行减法 1

问题描述

我被困在scala中的withColumn上执行减法运算。

val result = finalJoinedDf.withColumn("CTF", when(col("VPC") === null or col("FreightExpense") === null or col("FreightRevenue") === null or col("Cost") === null,  null)
                                  .otherwise(1 - col("VPC").cast(DoubleType)/100))

我的问题是我无法执行这个减法,它给出了以下错误。

在此处输入图像描述

即使我也无法执行加法。

请有人在这里帮助我

标签: scalaazure-databricks

解决方案


import org.apache.spark.sql.functions.{col, udf, when, lit}
import org.apache.spark.sql.types.DoubleType
import spark.implicits._

case class Test(VPC: Option[Int])

val df = Seq(Test(Some(1)), Test(Some(2)), Test(Some(3)), Test(None)).toDF()

val testUdf = udf((a: Double) => 1 - a / 100)

val df1 = df.withColumn("CTF", when(col("VPC").isNull,  lit(null).cast(DoubleType))
  .otherwise(testUdf(col("VPC").cast(DoubleType))))

df1.printSchema()
//  root
//  |-- VPC: integer (nullable = true)
//  |-- CTF: double (nullable = true)

df1.show(false)
//  +----+----+
//  |VPC |CTF |
//  +----+----+
//  |1   |0.99|
//  |2   |0.98|
//  |3   |0.97|
//  |null|null|
//  +----+----+

推荐阅读