【问题标题】:Extract columns in nested Spark DataFrame as scala Arrays将嵌套 Spark DataFrame 中的列提取为 scala 数组
【发布时间】:2017-12-06 13:57:39
【问题描述】:

我有一个 DataFrame myDf,其中包含一组点对(即 x 和 y 坐标),它具有以下架构:

myDf.printSchema

root
 |-- pts: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- x: float (nullable = true)
 |    |    |-- y: float (nullable = true)

我想获得 xy 作为单独的普通 Scala Array's。我想我需要应用爆炸功能,但我不知道如何。我尝试应用this 解决方案,但无法正常工作。

我正在使用 Spark 1.6.1 和 Scala 2.10

编辑:我意识到我误解了 Spark 的工作原理,只有在收集数据(或使用 UDF)时才能获取实际数组

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    假设myDf 是从json 文件中读取的DataFrame

    {
     "pts":[
        {
         "x":0.0,
         "y":0.1
        },
        {
         "x":1.0,
         "y":1.1
        },
        {
         "x":2.0,
         "y":2.1
        }
      ]
    }
    

    你可以这样explode

    Java:

    DataFrame pts = myDf.select(org.apache.spark.sql.functions.explode(df.col("pts")).as("pts"))
                        .select("pts.x", "pts.y");
    pts.printSchema();
    pts.show();
    

    斯卡拉:

    // Sorry I don't know Scala
    // I just interpreted from the above Java code
    // Code here may have some mistakes
    val pts = myDf.select(explode($"pts").as("pts"))
                  .select($"pts.x", $"pts.y")
    pts.printSchema()
    pts.show()
    

    这是打印出来的架构:

    root
     |-- x: double (nullable = true)
     |-- y: double (nullable = true)
    

    这是pts.show() 结果:

    +---+---+
    |  x|  y|
    +---+---+
    |0.0|0.1|
    |1.0|1.1|
    |2.0|2.1|
    +---+---+
    

    【讨论】:

    • 感谢提问者和回答者。你们让我很开心。使用 spark-xml 时我脱发了,你的解决方案很糟糕;-)
    【解决方案2】:

    有两种方法可以将积分作为plan scala Arrays:

    收集给司机:

    val localRows = myDf.take(10)
    val xs: Array[Float] = localRows.map(_.getAs[Float]("x"))
    val ys: Array[Float] = localRows.map(_.getAs[Float]("y"))
    

    或在 UDF 内:

    val processArr = udf((pts:WrappedArray[Row]) => {
    
      val xs: Array[Float] = pts.map(_.getAs[Float]("x")).array
      val ys: Array[Float] = pts.map(_.getAs[Float]("y")).array
      //...do something with it
    })
    

    }

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 2019-09-26
      • 2020-10-02
      • 1970-01-01
      • 2020-11-08
      • 2019-06-13
      • 1970-01-01
      • 2020-09-02
      • 2021-03-27
      相关资源
      最近更新 更多