【问题标题】:Error on fold when reducing in Spark / Scala在 Spark / Scala 中减少时折叠错误
【发布时间】:2019-02-04 18:38:42
【问题描述】:

鉴于我有一个包含一些列的数据框:

为什么这不起作用?

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)))

使用著名的 lit 函数似乎可以平滑一些事情,但我不知道为什么。

+---+----+----+----+----+----+------+
| ID|var1|var2|var3|var4|var5|concat|
+---+----+----+----+----+----+------+
|  a|   5|   7|   9|  12|  13|  46.0|
+---+----+----+----+----+----+------+

【问题讨论】:

    标签: scala apache-spark fold


    【解决方案1】:

    先决条件:

    • 根据编译器消息和 API 使用情况,我们可以推断出 columnsToConcatSeq[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) =&gt; Int 方法Int (错误已经列出了可用的方法,而且这种方法不存在也不足为奇),在当前范围内也不存在从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 &lt;: Any 类型约束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2015-02-04
      • 2013-12-27
      • 2014-05-29
      相关资源
      最近更新 更多