【问题标题】:How to perform subtraction 1 with column value如何用列值执行减法 1
【发布时间】:2021-08-18 13:13:07
【问题描述】:
我被困在 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))
我的问题是我无法执行这个减法,它给出了以下错误。
即使我也无法执行加法。
请有人在这里帮助我
【问题讨论】:
标签:
scala
azure-databricks
【解决方案1】:
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|
// +----+----+