【问题标题】:Spark-Scala : Create split rows based on the value of other columnSpark-Scala:根据其他列的值创建拆分行
【发布时间】:2023-01-05 23:20:20
【问题描述】:

我有如下输入

id size
1 4
2 2

输出 - 如果输入为 4(大小列)拆分 4 次(1-4)并且如果输入大小列值为 2 拆分它 1-2次。

id size
1 1
1 2
1 3
1 4
2 1
2 2

【问题讨论】:

    标签: scala apache-spark pyspark scala-spark


    【解决方案1】:

    您可以使用 Seq.range 将您的 size 列变成递增序列,然后分解数组。是这样的:

    import spark.implicits._
    import org.apache.spark.sql.functions.{explode, col}
    
    // Original dataframe
    val df = Seq((1,4), (2,2)).toDF("id", "size")
    
    // Mapping over this dataframe: turning each row into (idx, array)
    val df_with_array = df
      .map(row => {
        (row.getInt(0), Seq.range(1, row.getInt(1) + 1)) 
      }).toDF("id", "array")
    
    df_with_array.show()
    +---+------------+
    | id|       array|
    +---+------------+
    |  1|[1, 2, 3, 4]|
    |  2|      [1, 2]|
    +---+------------+
    
    // Finally selecting the wanted columns, exploding the array column
    val output = df_with_array.select(col("id"), explode(col("array")))
    
    output.show()
    +---+---+
    | id|col|
    +---+---+
    |  1|  1|
    |  1|  2|
    |  1|  3|
    |  1|  4|
    |  2|  1|
    |  2|  2|
    +---+---+
    
    

    【讨论】:

      【解决方案2】:

      您可以使用 sequence 函数创建从 1 到 size 的序列数组,然后将其分解:

      import org.apache.spark.sql.functions._
      val df = Seq((1,4), (2,2)).toDF("id", "size")
      df
        .withColumn("size", explode(sequence(lit(1), col("size"))))
        .show(false)
      

      输出将是:

      +---+----+
      |id |size|
      +---+----+
      |1  |1   |
      |1  |2   |
      |1  |3   |
      |1  |4   |
      |2  |1   |
      |2  |2   |
      +---+----+
      

      【讨论】:

        猜你喜欢
        • 2021-03-25
        • 1970-01-01
        • 2023-03-17
        • 2021-09-15
        • 1970-01-01
        • 2023-01-12
        • 2023-01-24
        • 2022-06-10
        相关资源
        最近更新 更多