You need to enable JavaScript to run this app. 如何在Spark Dataframe中获取非空值对应列名并生成新列
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spark Dataframe中获取非空值对应列名并生成新列

Spark DataFrame新增列取非空列列名解决方案

核心逻辑是通过when条件函数依次判断列是否非空,匹配成功就返回对应列名,支持两种常见开发语言的实现:

PySpark 实现

首先导入依赖函数:

from pyspark.sql.functions import when, col, lit, coalesce

直接调用withColumn新增result列即可:

# 此处df为你的原始DataFrame
df = df.withColumn("result",
    when(col("Col A").isNotNull(), lit("Col A"))
    .when(col("Col B").isNotNull(), lit("Col B"))
    # 可选补充:如果存在两列都为空/都非空的场景,可加otherwise指定默认值
    # .otherwise(lit("unknown"))
)

也可以用coalesce简化写法:

df = df.withColumn("result",
    coalesce(
        when(col("Col A").isNotNull(), "Col A"),
        when(col("Col B").isNotNull(), "Col B")
    )
)

Scala Spark 实现

先导入依赖函数:

import org.apache.spark.sql.functions.{when, col, lit, coalesce}

新增列逻辑:

// 此处df为你的原始DataFrame
val resDf = df.withColumn("result",
  when(col("Col A").isNotNull, lit("Col A"))
  .when(col("Col B").isNotNull, lit("Col B"))
  // 可选:.otherwise(lit("unknown"))
)

coalesce简化写法:

val resDf = df.withColumn("result",
  coalesce(
    when(col("Col A").isNotNull, "Col A"),
    when(col("Col B").isNotNull, "Col B")
  )
)

如果后续需要扩展更多列判断,只需要在链式调用里按优先级新增when条件即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 08:54:03