既然我有一些列的数据帧:
为什么这个不行?
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|
+---+----+----+----+----+----+------+
先决条件:
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
类型约束满意