如何在if else条件中的列中使用spark值-scala

fnatzsnv  于 2021-07-09  发布在  Spark
关注(0)|答案(1)|浏览(328)

我有下面的dataframe,我希望将列中的值与字符串进行比较,并将其用作if else语句中的条件。
Dataframe:

id   type       name
1    fruit     apple
2    toy       football
3   fruit      orange

我希望实现的是:

if(df("type") == "fruit"){
    //do something to the df
}else if ( df("type") == "toy"){
    //something else to the df
}

我试着用 val type= df.select("type").collectAsList().getString(0) 但这是不对的。有人能帮忙吗?非常感谢。我不认为这是一个重复的问题,因为我不想添加一个新的专栏。spark:有条件地向dataframe添加列,我不希望使用 withColumn

dgtucam1

dgtucam11#

dataframe的隐式类应该可以做到这一点,下面的代码(忽略我的疯狂导入?)

import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.Column
import org.apache.spark.sql.functions._
import spark.implicits._

implicit class typeTransform(df: DataFrame) {
    def tranformByType(typeCol: Column) = {
      if(df.filter(typeCol === lit("fruit")).count > 0) df // do something to df 
      //........ more if Statements
      else df// do something with df 
    }
}

用法可以是这样的

val someDf = Seq(("fruit", "1"), ("toy", "2")).toDF("type", "id").tranformByType(col("type"))

相关问题