将wrappedarray拆分为多个行和列

z8dt9xmd  于 2021-05-17  发布在  Spark
关注(0)|答案(1)|浏览(427)

我刚到斯卡拉。我正试着分开一个包裹,但没有成功。我有一个数据框,其中包含一行从xml转换的数据。
如果我跑了 df.printSchema 我得到:

root
 |-- WrappedArray: struct (nullable = true)
 |    |-- Response: struct (nullable = true)
 |    |    |-- Result: struct (nullable = true)
 |    |    |    |-- Cols: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- col1: string (nullable = true)
 |    |    |    |    |    |-- col2: string (nullable = true)
 |    |    |    |    |    |-- col3: string (nullable = true)
 |    |    |    |    |    |-- col4: string (nullable = true)
 |    |    |    |    |    |-- col5: long (nullable = true)
 |    |    |-- _xmlns: string (nullable = true)

如果我跑了 df.head() 我得到:

[[[[WrappedArray([1,2019-11-29T00:00:00,06:00,1 Center1,55]
 , [2,2020-03-28T00:00:00,06:00,2 Center2,57]
 , [3,2020-07-01T00:00:00,06:00,3 Center3,58])],https://centers.net/]]]

我想得到一个有5列的Dataframe,如下所示:

col1   col2                  col3    col4         col5
1      2019-11-29T00:00:00   06:00   1 Center1    55
2      2020-03-28T00:00:00   06:00   2 Center2    57
3      2020-07-01T00:00:00   06:00   3 Center3    58

我在stackoverflow上看到过很多类似于我的帖子,但是案例有点不同,因为wrapparrays已经被分成了多行。我试过(即collection.mutable.wrappedarray)调整它以适应我的情况,但我是scala的新手,这对我来说非常困难。
你能帮帮我吗?

yshpjwxd

yshpjwxd1#

您可以使用sparkDataframedsl这样做:

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

df.withColumn("exploded", explode(col("WrappedArray.Response.Result.Cols")))
  .select(
    col("exploded.col1").as("col1"),
    col("exploded.col2").as("col2"),
    col("exploded.col3").as("col3"),
    col("exploded.col4").as("col4"),
    col("exploded.col5").as("col5")
  )

这将分解模式中的数组,为每个元素创建一行,然后将数组元素中的每个col字段选择到自己的列中。

相关问题