PySpark groupby和max value selection

时间:2016-11-30 13:23:39

标签: python apache-spark pyspark apache-spark-sql pyspark-sql

我有一个像

这样的PySpark数据帧
 name   city     date
 satya  Mumbai  13/10/2016
 satya  Pune    02/11/2016
 satya  Mumbai  22/11/2016
 satya  Pune    29/11/2016
 satya  Delhi   30/11/2016
 panda  Delhi   29/11/2016
 brata  BBSR    28/11/2016
 brata  Goa     30/10/2016
 brata  Goa     30/10/2016

我需要为每个名字找出最喜欢的城市,并且逻辑是“如果城市在聚合'名称'+'城市'对上具有最大城市发生次数,则将城市视为优惠”。如果发现多个相同的事件,则考虑具有最新日期的城市。请解释一下:

d = df.groupby('name','city').count()
#name  city  count
brata Goa    2  #clear favourite
brata BBSR   1
panda Delhi  1  #as single so clear favourite
satya Pune   2  ##Confusion
satya Mumbai 2  ##confusion
satya Delhi  1   ##shd be discard as other cities having higher count than this city

#So get cities having max count
dd = d.groupby('name').agg(F.max('count').alias('count'))
ddd = dd.join(d,['name','count'],'left')
#name  count  city
 brata    2   Goa    #fav found
 panda    1   Delhi  #fav found
 satya    2   Mumbai #can't say
 satya    2   Pune   #can't say

如果是用户'satya',我需要回到trx_history并获取具有equal_max计数的城市的最新日期I:e来自最后交易的'Mumbai'或'Pune'(最大日期),将该城市视为fav_city。在这种情况下,'Pune'为'29/11 / 2016'是最新/最大日期。

但我无法进一步完成如何完成任务。

请帮我逻辑或如果有更好的解决方案(更快/更紧凑的方式),请建议。谢谢。

2 个答案:

答案 0 :(得分:4)

首先将日期转换为DateType

df_with_date = df.withColumn(
    "date",
    F.unix_timestamp("date", "dd/MM/yyyy").cast("timestamp").cast("date")
)

下一个groupBy用户和城市,但扩展聚合如下:

df_agg = (df_with_date
    .groupBy("name", "city")
    .agg(F.count("city").alias("count"), F.max("date").alias("max_date")))

定义一个窗口:

from pyspark.sql.window import Window

w = Window().partitionBy("name").orderBy(F.desc("count"), F.desc("max_date"))

添加排名:

df_with_rank = (df_agg
    .withColumn("rank", F.dense_rank().over(w)))

并过滤:

result = df_with_rank.where(F.col("rank") == 1)

您可以使用以下代码检测剩余的重复项:

import sys

final_w = Window().partitionBy("name").rowsBetween(-sys.maxsize, sys.maxsize)
result.withColumn("tie", F.count("*").over(final_w) != 1)

答案 1 :(得分:0)

d = df.groupby('name','city').count()
#name  city  count
brata Goa    2  #clear favourite
brata BBSR   1
panda Delhi  1  #as single so clear favourite
satya Pune   2  ##Confusion
satya Mumbai 2  ##confusion
satya Delhi  1   ##shd be discard as other cities having higher count than this city

#So get cities having max count
dd = d.groupby('name').count().sort(F.col('count').desc())
display(dd.take(1))