Scala 类型不匹配:预期字符串,实际列
我正在使用Spark 2.2.0和Scala 2.11对我的数据帧进行一些转换 这行代码Scala 类型不匹配:预期字符串,实际列,scala,apache-spark,spark-dataframe,Scala,Apache Spark,Spark Dataframe,我正在使用Spark 2.2.0和Scala 2.11对我的数据帧进行一些转换 这行代码Math.abs($“right.product\u price.asInstanceOf[Double]-$“left.product\u price.asInstanceOf[Double])出现问题。我想计算left.product\u price和right.product\u price之间的绝对差值。如果其中任何列包含null,则null将转换为0 但是,我得到一个错误:“类型不匹配:预期字符串,
Math.abs($“right.product\u price.asInstanceOf[Double]-$“left.product\u price.asInstanceOf[Double])
出现问题。我想计算left.product\u price
和right.product\u price
之间的绝对差值。如果其中任何列包含null
,则null
将转换为0
但是,我得到一个错误:“类型不匹配:预期字符串,实际列”。
如何以正确的方式进行此计算
val result = df.as("left")
// self-join by gender:
.join(df.as("right"), ($"left.gender" === $"right.gender")
// limit to 10 results per record:
.withColumn("rn", row_number().over(Window.partitionBy($"left.product_PK").orderBy($"right.product_PK")))
.filter($"rn <= 10").drop($"rn")
// group and collect_list to create products column:
.groupBy($"left.product_PK" as "product_PK")
.agg(collect_list(struct($"right.product_PK", Math.abs($"right.product_price".asInstanceOf[Double] - $"right.product_price".asInstanceOf[Double]))) as "products")
val result=df.as(“左”)
//按性别划分的自加入:
.join(df.as(“right”),($“left.gender”==$“right.gender”)
//每个记录最多10个结果:
.withColumn(“rn”,row_number()。在(Window.partitionBy($“left.product_PK”).orderBy($“right.product_PK”))上方)
.filter($“rn您不能使用Math.abs
,也不能使用asinstanceOf
。请使用SQL函数。abs
和cast
:
import org.apache.spark.sql.functions.abs
...
.agg(collect_list(struct(
$"right.product_PK",
abs($"right.product_price".cast("double)" - $"right.product_price".cast("double"))
)) as "products")
要将null
转换为0
添加合并
:
import org.apache.spark.sql.functions.{coalesce, lit}
coalesce(column, lit(0))
与此相同吗?:.withColumn(“绝对价格差异”,abs(coalesce($“right.product\u price”,lit(0))-coalesce($“left.product\u price”,lit(0))))。过滤器($“rn