【问题标题】:Loading nested array into spark dataframe column将嵌套数组加载到 spark 数据框列中
【发布时间】:2020-03-13 07:23:17
【问题描述】:

我有一个嵌套数组,看起来像

a = [[1,2],[2,3]]

我有一个流数据帧,看起来像

|system    |level|

+----------+-----+

|Test1     |1    |

|Test2     |3    |

我想将数组作为嵌套数组包含在第三列中。

|system    |level| Data |

+----------+-----+------+

|Test1     |1    |[[1,2],[2,3]]

我尝试了列和数组函数。但我不确定如何使用嵌套数组。

任何帮助将不胜感激。

【问题讨论】:

    标签: python arrays dataframe apache-spark pyspark


    【解决方案1】:

    在 scala API 中,我们可以使用“typedLit”函数在列中添加 Array 或 map 值。

    // 参考:https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

    这里是添加数组作为列值的示例代码。

    import org.apache.spark.sql.functions.typedLit
    
    val a = Seq((1,2),(2,3))
    val df1 = Seq(("Test1", 1), ("Test3", 3)).toDF("a", "b")
    
    df1.withColumn("new_col", typedLit(a)).show()
    

    // 输出

    +-----+---+----------------+
    |    a|  b|         new_col|
    +-----+---+----------------+
    |Test1|  1|[[1, 2], [2, 3]]|
    |Test3|  3|[[1, 2], [2, 3]]|
    +-----+---+----------------+
    

    我希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      如果您想将相同的数组添加到所有原始数据,则可以使用 sql 函数中的 TypedLit。看到这个答案:
      https://stackoverflow.com/a/32788650/12365294

      【讨论】:

      • 我确实试过这个。但我无法在 python 中导入“import org.apache.spark.sql.functions”。我在执行中包含了 jar 文件 org.apache.spark:spark-sql_2.11:2.4.4。但仍然没有运气。
      • 对于 pyspark 你需要 import "from pyspark.sql.functions import *"
      【解决方案3】:

      您可以添加一个新列,但您必须使用crossJoin

      a = [[1,2],[2,3]]
      
      df.crossJoin(spark.createDataFrame([a], "array<array<bigint>>")).show()
      
      +-------------------+----+------+----------------+
      |               date|hour| value|            data|
      +-------------------+----+------+----------------+
      |1984-01-01 00:00:00|   1|638.55|[[1, 2], [2, 3]]|
      |1984-01-01 00:00:00|   2|638.55|[[1, 2], [2, 3]]|
      |1984-01-01 00:00:00|   3|638.55|[[1, 2], [2, 3]]|
      |1984-01-01 00:00:00|   4|638.55|[[1, 2], [2, 3]]|
      |1984-01-01 00:00:00|   5|638.55|[[1, 2], [2, 3]]|
      +-------------------+----+------+----------------+
      

      【讨论】:

        猜你喜欢
        • 2020-12-30
        • 2021-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        相关资源
        最近更新 更多