PySpark - 选择每周 3 天、每月 3 周看到的用户
Posted
技术标签:
【中文标题】PySpark - 选择每周 3 天、每月 3 周看到的用户【英文标题】:PySpark - Select users seen for 3 days a week for 3 weeks a month 【发布时间】:2019-01-14 11:19:33 【问题描述】:我知道这是一个非常具体的问题,在 *** 上发布此类问题并不常见,但我处于一种奇怪的情况,即有一个可以解决我的问题的简单算法的想法,但无法实施它。因此我的问题。
我有一个数据框
|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 中以一种可扩展的方式执行此操作,但我不知道如何实现它。另外,如果你对算法有比我幼稚的方法更好的想法,那真的很有帮助。
【问题讨论】:
【参考方案1】:我建议使用 groupBy 函数来选择带有 where 选择器的用户:
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' )
【讨论】:
我得到一个:AttributeError: 'GroupedData' 对象没有属性 'countDistinct' 抱歉,我忘记了 'countDistinct' 周围的 'agg' 函数。检查编辑版本。【参考方案2】:@eakotelnikov 是正确的。
但如果有人遇到错误
NameError:名称“countDistinct”未定义
那么请在执行 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()
【讨论】:
以上是关于PySpark - 选择每周 3 天、每月 3 周看到的用户的主要内容,如果未能解决你的问题,请参考以下文章