【发布时间】: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
我有如下输入
| 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
您可以使用 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|
+---+---+
【讨论】:
您可以使用 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 |
+---+----+
【讨论】: