python - 计算 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 天。
解决方案
平均用户存在天数将是加权平均值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
推荐阅读
- flutter - Flutter Firestore 在 UTC 中节省时间
- wordpress - 执行热键时缺少字符
- javascript - 创建 HTML 元素的 Javascript 类
- java - 带有递归函数的Java返回
- javascript - AJAX 工具包 ConfirmButtonExtender 未打开确认窗口
- python - 计算 n 个数字的最大值、最小值和平均值
- vb.net - 如何从谷歌地图位置链接获取经度和纬度?
- python - rxpy 高效地组合 observables
- node.js - 热重载 HMR Webpack 在 Docker 容器 WSL2 上不起作用
- discord.js - 运行 eval 命令时无法发送空消息错误