将布尔列转换为具有约束的 Apache Spark (Scala) 数据框中的数字列?

Transform Boolean Column to Numerical Column in Apache Spark (Scala) data frame with constraints?

 val inputfile = sqlContext.read
        .format("com.databricks.spark.csv")
        .option("header", "true") 
        .option("inferSchema", "true") 
        .option("delimiter", "\t")
        .load("data")
 inputfile: org.apache.spark.sql.DataFrame = [a: string, b: bigint, c: boolean]
 val outputfile = inputfile.groupBy($"a",$"b").max($"c")

以上代码失败,因为 c 是一个布尔变量,聚合不能应用于布尔值。 Spark 中是否有一个函数可以将 true 值转换为 1 并将 false 转换为 0 用于 Spark 数据框的整列。

我尝试了以下方法(来源:How to change column types in Spark SQL's DataFrame?

 val inputfile = sqlContext.read
        .format("com.databricks.spark.csv")
        .option("header", "true") 
        .option("inferSchema", "true") 
        .option("delimiter", "\t")
        .load("data")
 val tempfile =inputfile.select("a","b","c").withColumn("c",toInt(inputfile("c")))   
 val outputfile = tempfile.groupBy($"a",$"b").max($"c")

以下问题: PySpark 的答案,但我想要一个专门用于 Scala 的函数。

感谢任何形式的帮助。

implicit def bool2int(b:Boolean) = if (b) 1 else 0

scala> false:Int
res4: Int = 0

scala> true:Int
res5: Int = 1

scala> val b=true
b: Boolean = true


scala> 2*b+1
res2: Int = 3

使用上面的函数并注册为UDF

val bool2int_udf = udf(bool2int _)

val tempfile =inputfile.select("a","b","c").withColumn("c",bool2int_UDF($("c")))

下面的代码对我有用。 @Achyuth 的回答提供了部分功能。然后,从这个问题中得出想法: 我能够使用 UDF 将 Achyuth answer 中的函数应用到数据框的整列。这是完整的代码。

 implicit def bool2int(b:Boolean) = if (b) 1 else 0
 val bool2int_udf = udf(bool2int _)
 val inputfile = sqlContext.read
        .format("com.databricks.spark.csv")
        .option("header", "true") 
        .option("inferSchema", "true") 
        .option("delimiter", "\t")
        .load("data") 
 val tempfile = inputfile.select("a","b","c").withColumn("c",bool2int_udf($"c"))
 val outputfile = tempfile.groupBy($"a",$"b").max($"c")

您不需要使用 udf 来执行此操作。如果要将布尔值转换为 int,可以将列类型转换为 int

val df2 = df1
  .withColumn("boolAsInt",$"bool".cast("Int")