You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于PySpark DataFrame其他列值新增行与列?

解决方案

要实现当c1和c2都有值时生成两行的需求,需要借助PySpark的array构造数组、explode拆分数组的能力,具体代码如下:

首先导入所需函数:

from pyspark.sql.functions import col, when, array, explode, lit

然后处理DataFrame:

# 构造临时数组列,根据不同情况生成对应元素
df = df.withColumn(
    'temp_array',
    when(
        col('c1').isNotNull() & col('c2').isNotNull(),
        array(col('c1'), col('c2'))  # 两列都非空时,数组包含两个值
    ).when(
        col('c1').isNotNull(),
        array(col('c1'))  # 仅c1非空时,数组只包含c1
    ).when(
        col('c2').isNotNull(),
        array(col('c2'))  # 仅c2非空时,数组只包含c2
    ).otherwise(
        array(lit(None))  # 两列都空时,数组包含null
    )
)

# 拆分数组生成多行,再删除临时列
df = df.withColumn('new_col', explode(col('temp_array'))).drop('temp_array')

逻辑说明

  1. 构造临时数组列:根据c1和c2的非空情况,生成对应元素的数组:
    • 两列都有值 → 数组包含c1和c2两个元素
    • 仅一列有值 → 数组只包含该列的值
    • 两列都空 → 数组包含一个null元素
  2. 拆分数组:使用explode函数将数组的每个元素拆分为单独的行,自动实现"两列都有值时生成两行"的需求
  3. 清理临时列:删除用于过渡的temp_array列,得到最终结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:29:57