从 Scala 中的 Spark Dataframe 分解 Array[(Int, Int)] 列

Explode Array[(Int, Int)] column from Spark Dataframe in Scala

我要分解数组[(Int, Int)]

输入:

colA newCol
1     [[11, 12],[13, 15]]
2     [[17, 91], [51, 72]]

输出:

colA newCol
1     11
1     13
2     17
2     51

我的架构如下所示:

 |-- colA: integer (nullable = true)
 |-- newCol: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- value: integer (nullable = true)
 |    |    |-- count: integer (nullable = true)

我试过下面这样的东西:

val res =  df.withColumn("tup", explode($"newCol")).select("colA", "tup")

res.select(col("colA"), col("tup")("value").as("uId"))

你可以试试这个。

val result = df.withColumn("resultColumn",explode(col("newCol").getItem("value")).select("colA","resultColumn")

所以你基本上是分解数组然后获取结构的第一个元素。

已编辑:

以下是我如何使用相同的架构创建数据框。

scala> import spark.implicits._

scala> val df = spark.sparkContext.parallelize(List((1),(2))).toDF("id")

scala> val df1 = df.withColumn("col2",array(struct(lit(1),lit(2)),struct(lit(3),lit(4))))

scala> df1.printSchema
root
 |-- id: integer (nullable = false)
 |-- col2: array (nullable = false)
 |    |-- element: struct (containsNull = false)
 |    |    |-- col1: integer (nullable = false)
 |    |    |-- col2: integer (nullable = false)


scala> df1.withColumn("resultColumn",explode(col("col2").getItem("col1"))).select("id","resultColumn").show
+---+------------+
| id|resultColumn|
+---+------------+
|  1|           1|
|  1|           3|
|  2|           1|
|  2|           3|
+---+------------+