[英]f.when output count with Pyspark
我想从我加入的 2 个表中按月获取注册用户总数和已识别用户总数。 请参阅所需的 output:
Month reg_users iden_users
Jan 300 600
Feb 250 500
Mar 100 200
但我得到一个错误:
when() 缺少 1 个必需的位置参数:“值”
使用的代码:
#registered vs identified
dim_customers = (spark.table(f'nn_squad7_{country}.dim_customers')
.filter(f.col('registration_date').between(start,end))
.withColumn('month', f.date_format(f.date_sub(f.col('registration_date'), 1), 'MMM'))
.selectExpr('customer_id','age','gender','registration_date','month','1 as registered')
)
df = (
spark.table(f'nn_squad7_{country}.fact_table')
.filter(f.col('date_key').between(start,end))
.filter(f.col('is_client_plus')==1)
.filter(f.col('source')=='tickets')
.filter(f.col('subtype')=='trx')
.filter(f.col('is_trx_ok') == 1)
.withColumn('week', f.date_format(f.date_sub(f.col('date_key'), 1), 'YYYY-ww'))
.withColumn('month', f.date_format(f.date_sub(f.col('date_key'), 1), 'MMM'))
.selectExpr('customer_id','1 as identified','date_key')
)
output2 = (dim_customers
.join(df,'customer_id','left')
.fillna(0, subset=['identified'])
.withColumn('month', f.date_format(f.date_sub(f.col('date_key'), 1), 'MMM'))
.groupby('month')
.agg(f.countDistinct('customer_id').alias('reg_users'),
)
.withColumn('iden_users',f.when((f.col('identified')==1)))
)
display(output2)
知道为什么我会收到此错误吗? 解决方案可以进行 2 次查询? 我的想法是连接表并在一个查询中一起完成所有操作。
我猜您想获得已identified = 1
的客户 ID 的不同计数。 您可以在聚合期间使用when
进行条件计数:
output2 = (dim_customers
.join(df,'customer_id','left')
.fillna(0, subset=['identified'])
.withColumn('month', f.date_format(f.date_sub(f.col('date_key'), 1), 'MMM'))
.groupby('month')
.agg(f.countDistinct('customer_id').alias('reg_users'),
f.countDistinct(
f.when(
(f.col('identified')==1),
f.col('customer_id')
)
).alias('iden_users')
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.