【问题标题】:Merging the results of a scala spark dataframe as an array of results in another dataframe's column将scala spark数据框的结果合并为另一个数据框列中的结果数组
【发布时间】:2019-01-08 00:37:48
【问题描述】:

有没有办法获取以下两个数据帧并通过 col0 字段将它们连接起来,产生下面的输出?

//数据帧1

val df1 = Seq(
  (1, 9, 100.1, 10),
).toDF("pk", "col0", "col1", "col2")

//数据帧2

val df2 = Seq(
  (1, 9 "a1", "b1"),
  (2, 9 "a2", "b2")
).toDF("pk", "col0", "str_col1", "str_col2")

//预期的数据帧结果

+---+-----+----+---------------------------+
| pk| col1|col2| new_arr_col               |
+---+-----+----+---------------------------+
|  1|100.1|  10|[[1,9,a1, b1],[2,9,a2, b2]]|
+---+-----+----+---------------------------+

【问题讨论】:

    标签: scala apache-spark dataframe apache-spark-sql


    【解决方案1】:
    import org.apache.spark.sql.functions._
    import spark.implicits._
    
    // creating new array column out of all df2 columns:
    val df2AsArray = df2.select($"col0", array(df2.columns.map(col): _*) as "new_arr_col")
    
    val result = df1.join(df2AsArray, "col0")
      .groupBy(df1.columns.map(col): _*) // grouping by all df1 columns
      .agg(collect_list("new_arr_col") as "new_arr_col") // collecting array of arrays
      .drop("col0")
    
    result.show(false)
    // +---+-----+----+--------------------------------------------------------+
    // |pk |col1 |col2|new_arr_col                                             |
    // +---+-----+----+--------------------------------------------------------+
    // |1  |100.1|10  |[WrappedArray(2, 9, a2, b2), WrappedArray(1, 9, a1, b1)]|
    // +---+-----+----+--------------------------------------------------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 2021-08-19
      • 1970-01-01
      • 2021-06-29
      • 2020-11-06
      • 2019-03-25
      • 2019-01-23
      • 1970-01-01
      相关资源
      最近更新 更多