如何在 Scala case class 中应用函数来转换数据帧

How to apply functions in Scala case class for transforming dataframes

这里很新。我正在尝试将数据框(具有 2 列 a 和 b)转换为大小写 class,在 A 列上使用函数 mathAdd,并将该列放入新的 C 列中。我知道函数 .withColumn 但我真的不知道如何将它们放在一起。以下是我对评论的尝试。有人可以帮忙吗?非常感谢。 *已编辑:我想使用 case class 的原因之一是因为我想保存这些函数以供重用。

  dfTest.createOrReplaceTempView("testTable") 

  case class testclass (a:Int,b:String){
     var result = 0    
     def mathAdd ={
        if (b=="apple"){
           result=a+1
        } else{
           result=a+2
   // but how to put 'var result' into a column? 
     }
   }  
 }

 var toTestClass = sqlContext.table("testTable").as[testclass] 
 toTestClass.mathAdd()
 //After this how can I convert this testclass back to dataframe?  

您可以通过简单的 when 函数和 withColumn api

实现您打算用 case class 做的事情
import org.apache.spark.sql.functions._    
df.withColumn("newCol", when(col("b") === "apple", col("a")+1) otherwise(col("a")+2))

所以我猜你不需要case class

您可以在 map 中调用您的实例方法:

case class testclass(a: Int, b: String) {
    var result = 0

    def mathAdd: Int = {
      if (b == "apple") {
        result = a + 1
      } else {
        result = a + 2
      }
      return result
    }
  }

val tansformed = sqlContext.table("testTable").as[testclass].map(tc => tc.mathAdd)

这会给你一个 Dataset[Int]

但我宁愿将 mathAdd 定义为一个单独的方法,通常 case 类 不被认为包含逻辑:

case class testclass(a: Int, b: String)

def mathAdd(tc: testclass): Int = {
  if (tc.b == "apple") {
    tc.a + 1
  } else {
    tc.a + 2
  }
}

val tansformed = sqlContext.table("testTable").as[testclass].map(tc => mathAdd(tc))