Spark DataFrame 按键将列值聚合到列表中 [英] Spark DataFrame aggregate column values by key into List
本文介绍了Spark DataFrame 按键将列值聚合到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 DataFrame
看起来像这样:
I have a DataFrame
that looks like this:
+-----------------+-------+
|Id | value |
+-----------------+-------+
| 1622| 139685|
| 1622| 182118|
| 1622| 127955|
| 3837|3224815|
| 1622| 727761|
| 1622| 155875|
| 3837|1504923|
| 1622| 139684|
+-----------------+-------+
我想把它变成:
+-----------------+-------------------------------------------+
|Id | value |
+-----------------+-------------------------------------------+
| 1622|139685,182118,127955,727761,155875,139684 |
| 3837|3224815,1504923 |
+-----------------+-------------------------------------------+
这仅适用于 DataFrame
函数还是我需要将其转换为 RDD
?
Is this possible with DataFrame
functions only or do I need to convert it to and RDD
?
推荐答案
DataFrame
API 可以实现.试试:
It is possible with the DataFrame
API. Try:
df.groupBy(col("Id"))
.agg(collect_list(col("value")) as "value")
如果你想要一个由 ,
分隔的 String
而不是 Array
,那么试试这个:
If instead of an Array
you want a String
separated by ,
, then try this:
df.groupBy(col("Id"))
.agg(collect_list(col("value")) as "value")
.withColumn("value", concat_ws(",", col("value")))
这篇关于Spark DataFrame 按键将列值聚合到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文