Pyspark-GroupBy和Count与WHERE结合

时间:2018-12-11 17:20:59

标签: pandas python-2.7 apache-spark group-by pyspark

说我有一份杂志订阅清单,像这样:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

现在,我想添加一列,以说明用户在当前订阅之前有多少次订阅。例如,如果这是用户的第一个预订,则新列的值应为0。如果他们在此预订之前开始有一个预订,则新列的值应为1。这是完整的期望输出:

subscription_id    user_id       created_at
 12384               1           2018-08-10
 83294               1           2018-06-03
 98234               1           2018-04-08
 24903               2           2018-05-08
 32843               2           2018-03-06
 09283               2           2018-04-07

我该如何做到这一点,最好是在PySpark中,因此不使用subscription_id user_id created_at users_previous_subs 12384 1 2018-08-10 2 83294 1 2018-06-03 1 98234 1 2018-04-08 0 24903 2 2018-05-08 2 32843 2 2018-04-06 1 09283 2 2018-03-07 0

让我知道是否不清楚。谢谢!

1 个答案:

答案 0 :(得分:4)

这可以归结为row_number的计算。

from pyspark.sql import Window
from pyspark.sql import functions as func
#Define a window
w = Window.partitionBy(df.user_id).orderBy(df.created_at)
#Add an extra column with rownumber
df.withColumn('prev_subs',func.row_number().over(w)-1)
df.show()

如果可以建立联系(例如,给定日期的用户超过1行),请使用dense_rank

df.withColumn('prev_subs',func.dense_rank().over(w)-1)