Spark根据现有列的映射值创建新列

时间:2019-06-24 22:09:20

标签: scala apache-spark apache-spark-sql user-defined-functions

我正在尝试将数据框中的一列的值映射到新值,并使用UDF将其放入新列中,但是我无法使UDF接受也不是列的参数。例如,我有一个这样的数据框dfOriginial

+-----------+-----+
|high_scores|count|
+-----------+-----+
|          9|    1|
|         21|    2|
|         23|    3|
|          7|    6|
+-----------+-----+

我正试图了解数值所属的垃圾箱,因此我可以像这样构造垃圾箱列表:

case class Bin(binMax:BigDecimal, binWidth:BigDecimal) {
    val binMin = binMax - binWidth

    // only one of the two evaluations can include an  "or=", otherwise a value could fit in 2 bins
    def fitsInBin(value: BigDecimal): Boolean = value > binMin && value <= binMax

    def rangeAsString(): String = {
        val sb = new StringBuilder()
        sb.append(trimDecimal(binMin)).append(" - ").append(trimDecimal(binMax))
        sb.toString()
    }
}

然后我要像这样转换我的旧数据框以制作dfBin

+-----------+-----+---------+
|high_scores|count|bin_range|
+-----------+-----+---------+
|          9|    1| 0 - 10  |
|         21|    2| 20 - 30 |
|         23|    3| 20 - 30 |
|          7|    6| 0 - 10  |
+-----------+-----+---------+

这样,我最终可以通过调用.groupBy("bin_range").count()来获取垃圾箱的实例数。

我试图通过将dfBin函数与UDF一起使用来生成withColumn

这是我尝试使用的UDF的代码:

val convertValueToBinRangeUDF = udf((value:String, binList:List[Bin]) => {
    val number = BigDecimal(value)
    val bin = binList.find( bin => bin.fitsInBin(number)).getOrElse(Bin(BigDecimal(0), BigDecimal(0)))
    bin.rangeAsString()
})

val binList = List(Bin(10, 10), Bin(20, 10), Bin(30, 10), Bin(40, 10), Bin(50, 10))

val dfBin = dfOriginal.withColumn("bin_range", convertValueToBinRangeUDF(col("high_scores"), binList))

但这给了我一个类型不匹配的信息:

Error:type mismatch;
 found   : List[Bin]
 required: org.apache.spark.sql.Column
        val valueCountsWithBin = valuesCounts.withColumn(binRangeCol, convertValueToBinRangeUDF(col(columnName), binList))

看到UDF的定义,我认为它应该可以很好地处理转换,但是显然没有任何想法吗?

2 个答案:

答案 0 :(得分:2)

问题是UDF的参数都应为列类型。一种解决方案是将binList转换为列,然后将其传递给UDF,类似于当前代码。

但是,稍微调整UDF并将其变成def更为简单。这样,您可以轻松传递其他非列类型的数据:

def convertValueToBinRangeUDF(binList: List[Bin]) = udf((value:String) => {
  val number = BigDecimal(value)
  val bin = binList.find( bin => bin.fitsInBin(number)).getOrElse(Bin(BigDecimal(0), BigDecimal(0)))
  bin.rangeAsString()
})

用法:

val dfBin = valuesCounts.withColumn("bin_range", convertValueToBinRangeUDF(binList)($"columnName"))

答案 1 :(得分:1)

尝试一下-

scala> case class Bin(binMax:BigDecimal, binWidth:BigDecimal) {
     |     val binMin = binMax - binWidth
     |
     |     // only one of the two evaluations can include an  "or=", otherwise a value could fit in 2 bins
     |     def fitsInBin(value: BigDecimal): Boolean = value > binMin && value <= binMax
     |
     |    def rangeAsString(): String = {
     |       val sb = new StringBuilder()
     |       sb.append(binMin).append(" - ").append(binMax)
     |       sb.toString()
     |     }
     | }
defined class Bin


scala> val binList = List(Bin(10, 10), Bin(20, 10), Bin(30, 10), Bin(40, 10), Bin(50, 10))
binList: List[Bin] = List(Bin(10,10), Bin(20,10), Bin(30,10), Bin(40,10), Bin(50,10))


scala> spark.udf.register("convertValueToBinRangeUDF", (value: String) => {
     |     val number = BigDecimal(value)
     |     val bin = binList.find( bin => bin.fitsInBin(number)).getOrElse(Bin(BigDecimal(0), BigDecimal(0)))
     |     bin.rangeAsString()
     | })
res13: org.apache.spark.sql.expressions.UserDefinedFunction = UserDefinedFunction(<function1>,StringType,Some(List(StringType)))


//-- Testing with one record

scala> val dfOriginal = spark.sql(s""" select "9" as `high_scores`, "1" as count """)
dfOriginal: org.apache.spark.sql.DataFrame = [high_scores: string, count: string]


scala> dfOriginal.createOrReplaceTempView("dfOriginal")

scala> val dfBin = spark.sql(s"""  select high_scores, count, convertValueToBinRangeUDF(high_scores) as bin_range from dfOriginal """)
dfBin: org.apache.spark.sql.DataFrame = [high_scores: string, count: string ... 1 more field]

scala> dfBin.show(false)
+-----------+-----+---------+
|high_scores|count|bin_range|
+-----------+-----+---------+
|9          |1    |0 - 10   |
+-----------+-----+---------+

希望这会有所帮助。