使用 pyspark 分组、排名和聚合火花数据框 [英] Group By, Rank and aggregate spark data frame using pyspark
本文介绍了使用 pyspark 分组、排名和聚合火花数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据框:
I have a dataframe that looks like:
A B C
---------------
A1 B1 0.8
A1 B2 0.55
A1 B3 0.43
A2 B1 0.7
A2 B2 0.5
A2 B3 0.5
A3 B1 0.2
A3 B2 0.3
A3 B3 0.4
如何将C"列转换为每列 A 的相对排名(更高的分数-> 更好的排名)?预期输出:
How do I convert the column 'C' to the relative rank(higher score->better rank) per column A? Expected Output:
A B Rank
---------------
A1 B1 1
A1 B2 2
A1 B3 3
A2 B1 1
A2 B2 2
A2 B3 2
A3 B1 3
A3 B2 2
A3 B3 1
我想要达到的最终状态是聚合列 B 并存储每个 A 的排名:
The ultimate state I want to reach is to aggregate column B and store the ranks for each A:
示例:
B Ranks
B1 [1,1,3]
B2 [2,2,2]
B3 [3,2,1]
推荐答案
添加排名:
from pyspark.sql.functions import *
from pyspark.sql.window import Window
ranked = df.withColumn(
"rank", dense_rank().over(Window.partitionBy("A").orderBy(desc("C"))))
分组依据:
grouped = ranked.groupBy("B").agg(collect_list(struct("A", "rank")).alias("tmp"))
排序和选择:
grouped.select("B", sort_array("tmp")["rank"].alias("ranks"))
使用 Spark 2.1.0 测试.
Tested with Spark 2.1.0.
这篇关于使用 pyspark 分组、排名和聚合火花数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文