gpt4 book ai didi

python - 在pyspark中链接多个groupBy

转载 作者:行者123 更新时间:2023-11-30 22:15:51 24 4
gpt4 key购买 nike

我的数据如下所示:

   id | duration | action1 | action2 | ...
---------------------------------------------
1 | 10 | A | D
1 | 10 | B | E
2 | 25 | A | E
1 | 7 | A | G

我想按 ID 将其分组(效果很好!):

df.rdd.groupBy(lambda x: x['id']).mapValues(list).collect()

现在我想按持续时间对每个组中的值进行分组,以获得如下所示的结果:

    [(id=1,
((duration=10,[(action1=A,action2=D),(action1=B,action2=E),
(duration=7,(action1=A,action2=G)),

(id=2,
((duration=25,(action1=A,action2=E)))]

这是我不知道如何进行嵌套分组的地方。有什么建议吗?

最佳答案

无需序列化为rdd。以下是按多个列进行分组并将其余列聚合到列表中的通用方法,而无需对所有列进行硬编码:

from pyspark.sql.functions import collect_list
grouping_cols = ["id", "duration"]
other_cols = [c for c in df.columns if c not in grouping_cols]
df.groupBy(grouping_cols).agg(*[collect_list(c).alias(c) for c in other_cols]).show()
#+---+--------+-------+-------+
#| id|duration|action1|action2|
#+---+--------+-------+-------+
#| 1| 10| [A, B]| [D, E]|
#| 2| 25| [A]| [E]|
#| 1| 7| [A]| [G]|
#+---+--------+-------+-------+

更新

如果您需要preserve the order在这些操作中,最好的方法是将 pyspark.sql.WindoworderBy() 结合使用。这是因为对于 groupBy() 是否遵循 orderBy() maintains that order 似乎存在一些歧义。 .

假设您的时间戳存储在“ts”列中。您应该能够执行以下操作:

from pyspark.sql import Window
w = Window.partitionBy(grouping_cols).orderBy("ts")
grouped_df = df.select(
*(grouping_cols + [collect_list(c).over(w).alias(c) for c in other_cols])
).distinct()

关于python - 在pyspark中链接多个groupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50161556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com