在火花/ Scala的上折叠误差减小时

问题描述 投票:-2回答:1

既然我有一些列的数据帧:

为什么这个不行?

val output3b = input.withColumn("sum", columnsToConcat.foldLeft(0)((x,y)=>(x+y)))

notebook:16: error: overloaded method value + with alternatives:
 (x: Int)Int <and>
 (x: Char)Int <and>
 (x: Short)Int <and>
 (x: Byte)Int
cannot be applied to (org.apache.spark.sql.Column)
val output3b = input.withColumn("sum", columnsToConcat.foldLeft(0)((x,y)=>(x+y))) // does work
                                                                           ^
notebook:16: error: type mismatch;
found   : Int
required: org.apache.spark.sql.Column
val output3b = input.withColumn("sum", columnsToConcat.foldLeft(0)((x,y)=>(x+y)))  

但这个呢?

val output3a = input.withColumn("concat", columnsToConcat.foldLeft(lit(0))((x,y)=>(x+y)))

使用著名的照明功能似乎平稳了一些东西,但我不知道为什么。

+---+----+----+----+----+----+------+
| ID|var1|var2|var3|var4|var5|concat|
+---+----+----+----+----+----+------+
|  a|   5|   7|   9|  12|  13|  46.0|
+---+----+----+----+----+----+------+
scala apache-spark fold
1个回答
2
投票

先决条件:

  • 基于编译器的消息,我们可以推断,columnsToConcat的API使用是Seq[o.a.s.sql.Column]或同等学历。
  • 按照惯例foldLeft方法需要的功能映射到所述蓄能器(初始值)。这里的Seq.foldLeft signature def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
  • + Scala中是一种方法,特别为.+呼叫的语法糖。

这意味着,在以下情况下:

columnsToConcat.foldLeft(0)((x,y)=>(x+y))

columnsToConcat.foldLeft(0)((x: Int, y: Column) => x + y)

和你问+(累加器的推断类型 - Int)的0方法,由于Int - 并没有对+ (org.apache.spark.sql.Column) => Int Int方法(错误已经列出了可用的方法,这是很难意想不到的是,这样的方法没有按“T存在),也不存在,在当前的范围内,一个隐式转换从Int于任何类型的,其提供这样的方法。

在第二种情况下,你问

columnsToConcat.foldLeft(lit(0))((x,y)=>(x+y))

columnsToConcat.foldLeft(lit(0))((x: Column, y: Column) => x + y)

+Column.+(如type of lit(0) is Column)和这样的方法,which acceptsAny并返回Column,存在。由于Column <: Any类型约束满意

© www.soinside.com 2019 - 2024. All rights reserved.