PySpark中when.otherwise正确返回原列实际值的实现方案
PySpark独立会话数分箱逻辑修正
问题本质
PySpark在解析when/otherwise分支的传入参数时,有固定的识别规则:
- 未通过
f.col()、f.lit()标记的字符串,会被统一当作固定字面值处理 - 之前在otherwise分支传入的
'total_sessions'没有加列引用标记,所以直接被当成普通文本输出,根本不会去匹配同名字段的值 - 两个分支的输出类型必须保持一致:when分支返回的是字符串类型的
'+3',如果otherwise直接返回数值型的会话计数,会触发类型不匹配的报错
代码调整点
- 把otherwise分支里的字段引用通过
f.col('total_sessions')显式标记,读取单元格的实际计数 - 把引用的数值型计数通过
.cast('string')转成字符串类型,和when分支的输出类型对齐 - 给when分支的固定值加上
f.lit()标记,明确区分固定字面值和字段引用,避免后续维护混淆
可直接运行的修正代码
import pyspark.sql.functions as f session = (spark.table(f'nn_team5_{country}.fact_table') .filter(f.col('date_key').between(start, end)) .filter(f.col('is_client_plus') == 1) .filter(f.col('source') == 'session') .filter(f.col('subtype') == 'events') .groupby('customer_id') .agg(f.countDistinct('ga_session_id').alias('total_sessions')) .withColumn( 'session_count', f.when(f.col('total_sessions') >= 3, f.lit('+3')) .otherwise(f.col('total_sessions').cast('string')) ) ) display(session)
运行后的匹配效果
customer_id total_sessions session_count 484635 2 2 483635 40 +3 484005 1 1 484688 3 +3 184635 4 +3
内容的提问来源于stack exchange,提问作者frenchast
相关产品推荐
相关产品推荐

