【发布时间】:2018-03-13 04:29:16
【问题描述】:
我正在尝试根据 id 对实体进行分组,运行以下代码我有这个数据框:
val pet_type_count = pet_list.groupBy("id","pets_type").count()
pet_type_count.sort("id").limit(20).show
+----------+---------------------+-----+
| id| pets_type|count|
+----------+---------------------+-----+
| 0| 0| 2|
| 1| 0| 3|
| 1| 3| 3|
| 10| 0| 4|
| 10| 1| 1|
| 13| 0| 3|
| 16| 1| 3|
| 17| 1| 1|
| 18| 1| 2|
| 18| 0| 1|
| 19| 1| 7|
+----------+---------------------+-----+
我想按 id 对分组的结果进行分组,现在返回每个 id 的元组列表,这样我就可以为每个 id 应用以下 udf:
val agg_udf = udf { (v1: List[Tuple2[String, String]]) =>
var feature_vector = Array.fill(5)(0)
for (row <- v1) {
val index = (5 - row._1.toInt)
vector(index) = row._2.toInt
}
vector
}
val pet_vector_included = pet_type_count.groupBy("id").agg(agg_udf(col("pets_type_count")).alias("pet_count_vector"))
为此我需要获得以下信息:
+----------+---------------------+-----+
| id| pets_type_count|
+----------+---------------------+-----+
| 0| (0,2)|
| 1| (0,3)|
| | (3,3)|
| 10| (0,4)|
| | (1,1)|
| 13| (0,3)|
| 16| (1,3)|
| 17| (1,1)|
| 18| (1,2)|
| | (0,1)|
| 19| (1,7)|
+----------+---------------------+-----+
我无法弄清楚如何在 id 上的 groupby 之后获取元组。任何帮助将不胜感激!
【问题讨论】:
标签: scala apache-spark-sql aggregate user-defined-functions