【问题标题】:split WrappedArray into multiple rows and columns将 WrappedArray 拆分为多行和多列
【发布时间】:2020-11-22 18:55:15
【问题描述】:

我是 scala 的新手。我正在尝试拆分 WrappedArray,但没有成功。我有一个数据框,其中包含一行我从 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 列的数据框,如下所示:

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 上看到了很多与我的类似的帖子,但情况有点不同,因为 wrapArrays 已经分成多行。我已经尝试(即collection.mutable.WrappedArray)来调整它以适应我的情况,但我是scala的新手,这对我来说非常难以承受。

你能帮帮我吗?

【问题讨论】:

    标签: xml scala apache-spark databricks


    【解决方案1】:

    您可以使用 spark 数据帧 dsl 来执行此操作:

    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 字段选择到其自己的列中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多