【问题标题】:Create column with nested list aggregation in Dataframe在 Dataframe 中创建具有嵌套列表聚合的列
【发布时间】:2018-02-27 17:28:23
【问题描述】:

我有这种结构的数据框

val df = Seq(
  ("john", "tomato", 1),
  ("john", "carrot", 4),
  ("bill", "apple", 1),
  ("john", "tomato", 2),
  ("bill", "taco", 2)      
).toDF("name", "food", "price")

我需要像这样聚合嵌套列表

name | acc                       |
-----+---------------------------+
john |[(tomato, 3), (carrot, 4)] |
bill |[(apple, 1), (taco,2 )]    |

我尝试过这种方式,但它不正确。

 dff.groupBy($"name")
  .agg(collect_list(struct($"food", $"price")).as("foods"))
  .show(false)
+----+------------------------------------+
|name|set                                 |
+----+------------------------------------+
|john|[[tomato,1], [carrot,4], [tomato,2]]|
|bill|[[apple,1], [taco,2]]               |
+----+------------------------------------+

我怎样才能得到它?

【问题讨论】:

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


    【解决方案1】:

    您需要两个groupByaggregations 并使用collect_liststructsum 内置函数

    import org.apache.spark.sql.functions._
    df.groupBy("name", "food").agg(sum("price").as("price"))
      .groupBy("name").agg(collect_list(struct("food", "price")).as("acc"))
    

    您将输出dataframe

    +----+------------------------+
    |name|acc                     |
    +----+------------------------+
    |john|[[carrot,4], [tomato,3]]|
    |bill|[[taco,2], [apple,1]]   |
    +----+------------------------+
    

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 2017-06-26
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      相关资源
      最近更新 更多