Apache spark PySpark-选择每周3天、每月3周的用户
我知道这是一个非常具体的问题,通常不会在stackoverflow上发布此类问题,但我遇到了一个奇怪的情况,我想到了一个简单的算法来解决我的问题,但无法实现它。这就是我的问题 我有一个数据框Apache spark PySpark-选择每周3天、每月3周的用户,apache-spark,pyspark,apache-spark-sql,pyspark-sql,Apache Spark,Pyspark,Apache Spark Sql,Pyspark Sql,我知道这是一个非常具体的问题,通常不会在stackoverflow上发布此类问题,但我遇到了一个奇怪的情况,我想到了一个简单的算法来解决我的问题,但无法实现它。这就是我的问题 我有一个数据框 |user_id| action | day | week | ------------------------------ | d25as | AB | 2 | 1 | | d25as | AB | 3 | 2 | | d25as | AB | 5 | 1
|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周。“日”列从1到31,“周”列从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选择器选择用户:
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' )
@埃科特尼科夫是正确的 但如果有人面临错误 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()
我得到一个:AttributeError:'GroupedData'对象没有属性'countDistinct',对不起,我忘记了'countDistinct'附近的'agg'函数。检查编辑版本。