首页 > 解决方案 > 计算 Pyspark 中的平均用户存在

问题描述

我有一个包含两列的数据框days,表示用户被看到的天数,以及users计算用户被看到的天数。

+----+---------------+
|days|number_of_users|
+----+---------------+
|   2|           3922|
|   3|           1750|
|   4|            883|
|   5|            563|
|   6|            319|
|   7|            157|
|   8|             79|
|   9|             31|
|  10|              9|
|  11|              2|
+----+---------------+

看到 2 天的用户(此处为 3922)没有看到 3,4 天等。因此每个存储桶都包含一组唯一的用户。如何从此数据框中计算平均用户存在?

我正在考虑采取 a 之类的sum_i[users(i)*days(i)] / 30方法,其中 30 是该月的总天数。但是我不确定我该怎么做,或者它是否是正确的公式。

编辑:AVERAGE USER PRESENCE 是指看到用户的平均天数,例如,从上表中可以看到 3.5 天。

标签: pythonapache-sparkpysparkpyspark-sql

解决方案


平均用户存在天数将是加权平均值sum_i[users(i)*days(i)] / sum_i[users(i)]-

#Create the DataFrame
from pyspark.sql.functions import col, lit, sum
df = spark.createDataFrame([(2,3922),(3,1750),(4,883),(5,563),(6,319),(7,157),(8,79),
                            (9,31),(10,9),(11,2)], schema = ['days','number_of_users'])

#Calculating the weighted mean.
df = df.withColumn('Dummy',lit('Dummy'))
df = df.groupBy('Dummy').agg((sum(col('number_of_users') * col('days'))/sum(col('number_of_users'))).alias('avg_user_presence')).drop('Dummy')
df.show()
+------------------+
| avg_user_presence|
+------------------+
|3.0430330524951392|
+------------------+

交叉检查:

(2*3922+3*1750+4*883+5*563+6*319+7*157+8*79+9*31+10*9+11*2)/(3922+1750+883+563+319+157+79+31+9+2)
= 23477/7715
= 3.0403

推荐阅读