scala - 如何使用列值执行减法 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))
我的问题是我无法执行这个减法,它给出了以下错误。
即使我也无法执行加法。
请有人在这里帮助我
解决方案
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|
// +----+----+
推荐阅读
- java - 卡夫卡和 OpenJDK
- azure - Azure 函数 - 事件中心触发器已停止
- c# - 如何动态创建 XML 文件?
- laravel - Laravel Model::find() 自动按 id 对结果进行排序,如何停止呢?
- google-apps-script - 如何在 GAS 中运行/调试私有函数?
- python - settimeout() 忽略 Try/Except 的异常 - Python
- scrapy - 将项目(或其他变量)传递给 scrapy 的中间件(或其他模块)。
- build - Thinlto 的并发性在并行构建系统中有用吗?
- google-cloud-platform - 查看 Dataflow 如何进行融合优化的最佳方法是什么
- python - Discord.py Self Bot 使用重写