PySpark - Select 用户每周看 3 天,每月看 3 周

PySpark - Select users seen for 3 days a week for 3 weeks a month

我知道这是一个非常具体的问题,在 Whosebug 上 post 这种问题并不常见,但我处于一种奇怪的情况,因为我有一种天真的算法可以解决我的问题问题,但无法实施。因此我的问题。

我有一个数据框

|user_id| action | day | week |
------------------------------
| d25as | AB     | 2   | 1    |
| d25as | AB     | 3   | 2    |
| d25as | AB     | 5   | 1    | 
| m3562 | AB     | 1   | 3    |
| m3562 | AB     | 7   | 1    |
| m3562 | AB     | 9   | 1    |
| ha42a | AB     | 3   | 2    |
| ha42a | AB     | 4   | 3    |
| ha42a | AB     | 5   | 1    |

我想创建一个数据框,其中的用户似乎每周至少 3 天 每月至少 3 周。 "day" 列从 1 到 31,"week" 列从 1 到 4。

我的想法是:

split dataframe into 4 dataframes for each week
for every week_dataframe count days seen per user. 
count for every user how many weeks with >= 3 days they were seen.
only add to the new df the users seen for >= 3 such weeks. 

现在我需要在 Spark 中以一种可扩展的方式执行此操作,但我不知道如何实现它。另外,如果你对算法的想法比我天真的方法更好,那真的很有帮助。

我建议使用 groupBy 函数来选择带有 where selector 的用户:

df.groupBy('user_id', 'week')\
.agg(countDistinct('day').alias('days_per_week'))\
.where('days_per_week >= 3')\
.groupBy('user_id')\
.agg(count('week').alias('weeks_per_user'))\
.where('weeks_per_user >= 3' )

@eakotelnikov 是正确的。

但是如果有人遇到错误

NameError: name 'countDistinct' is not defined

然后请在执行 eakotelnikov 解决方案之前使用以下语句

from pyspark.sql.functions import *

为这个问题添加另一个解决方案

tdf.registerTempTable("tbl")

outdf = spark.sql(""" 
select user_id , count(*) as weeks_per_user from
( select user_id , week , count(*) as days_per_week 
  from tbl 
  group by user_id , week  
  having count(*) >= 3
 ) x
group by user_id
having count(*) >= 3
""")

outdf.show()