【问题标题】:spark dataframe: how to explode a IntegerType columnspark dataframe:如何分解 IntegerType 列
【发布时间】:2017-04-13 06:54:28
【问题描述】:
val schema = StructType(Array(StructField("id", IntegerType, false),StructField("num", IntegerType, false)))

我想通过每个id生成从0到num的连续数。 我不知道该怎么办。。 谢谢

data and result here !!!

【问题讨论】:

  • 添加代码格式

标签: scala apache-spark dataframe explode


【解决方案1】:

你可以使用UDFexplode函数:

import org.apache.spark.sql.functions.{udf, explode}

val range = udf((i: Int) => (0 to i).toArray)
df.withColumn("num", explode(range($"num")))

【讨论】:

    【解决方案2】:

    试试DataFrame.explode

    df.explode(col("id"), col("num")) {case row: Row =>
        val id = row(0).asInstanceOf[Int]
        val num = row(1).asInstanceOf[Int]
        (0 to num).map((id, _))
    }
    

    或者在 RDD 领域,您可以使用 flatmap 来实现:

    df.rdd.flatMap(x => (0 to x._2).map((x._1, _)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多