You need to enable JavaScript to run this app. PySpark实现多列最大值0/1标识拆分为独立行的方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

PySpark实现多列最大值0/1标识拆分为独立行的方案咨询

PySpark 多最大值行拆分实现方案

完整代码

columns = ['cat_1', 'cat_2', 'cat_3']

(
    test_df_spark
    # 已实现的最大值识别与0/1转换逻辑
    .withColumn('max_value', F.greatest(*columns))
    .select(
        'id',
        *[F.when(F.col(c) == F.col('max_value'), F.lit(1)).otherwise(F.lit(0)).alias(c) for c in columns]
    )
    # 新增:收集所有值为1的列名,过滤空值生成数组
    .withColumn(
        'max_cols',
        F.filter(
            F.array(*[F.when(F.col(c) == 1, F.lit(c)) for c in columns]),
            lambda x: x.isNotNull()
        )
    )
    # 新增:炸开数组,每个最大值列生成独立行
    .withColumn('max_col', F.explode(F.col('max_cols')))
    # 新增:基于当前行的最大值列名生成最终0/1结果
    .select(
        'id',
        *[F.when(F.col('max_col') == F.lit(c), F.lit(1)).otherwise(F.lit(0)).alias(c) for c in columns]
    )
    .show()
)

运行输出

+---+-----+-----+-----+
| id|cat_1|cat_2|cat_3|
+---+-----+-----+-----+
|  1|    1|    0|    0|
|  1|    0|    1|    0|
+---+-----+-----+-----+

适配说明

  • 支持任意数量的行级最大值列拆分场景,后续新增cat列时仅需修改columns列表即可复用全部逻辑
  • 若需兼容空最大值的边缘场景,可将F.explode替换为F.explode_outer避免行丢失
  • 若PySpark版本低于2.4不支持数组filter的lambda语法,可将max_cols的构造逻辑替换为:
    .withColumn(
        'max_cols',
        F.array_remove(
            F.array(*[F.when(F.col(c) == 1, F.lit(c)).otherwise(F.lit('')) for c in columns]),
            ''
        )
    )
    

内容的提问来源于stack exchange,提问作者itscarlayall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 07:36:05