使用pyspark分组,排序和汇总Spark数据框架 [英] Group By, Rank and aggregate spark data frame using pyspark

查看:1713
本文介绍了使用pyspark分组,排序和汇总Spark数据框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

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分组,排序和汇总Spark数据框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆