这里很新。我试图将数据帧(带有2列a和b)转换为case类,在列A上使用函数mathAdd
,并将列放在新列C中。我知道函数{{1但实际上我并不知道如何把它们放在一起。以下是我的评论尝试。有人可以帮忙吗?非常感谢。 *编辑:我想使用案例类的原因之一是因为我想保存这些函数以供重用。
.withColumn
答案 0 :(得分:1)
使用简单case class
函数和when
api
withColumn
来实现您的目标
import org.apache.spark.sql.functions._
df.withColumn("newCol", when(col("b") === "apple", col("a")+1) otherwise(col("a")+2))
所以我猜你不需要case class
。
答案 1 :(得分:1)
您只需在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))