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

PySpark:根据Column A值从B/C列取值生成New列

PySpark 条件生成新列解决方案

你需要基于Column A的条件值直接生成新列,不需要过滤数据,用PySpark的when()和otherwise()函数就能实现需求:

步骤1:导入必要模块

from pyspark.sql import SparkSession
from pyspark.sql.functions import when

步骤2:创建示例DataFrame

# 初始化SparkSession
spark = SparkSession.builder.appName("ConditionalColumnDemo").getOrCreate()

# 构建示例数据
sample_data = [
    (1210, 100, 200),
    (1300, 70, 50),
    (1200, 10, 50),
    (1310, 15, 300)
]
column_names = ["Column A", "Column B", "Column C"]
df = spark.createDataFrame(sample_data, column_names)

步骤3:添加条件判断的New列

# 生成New列:满足Column A>=1300取Column B,否则取Column C
result_df = df.withColumn(
    "New",
    when(df["Column A"] >= 1300, df["Column B"]).otherwise(df["Column C"])
)

# 查看结果
result_df.show()

执行后会输出符合要求的结果:

+---------+---------+---------+---+
|Column A |Column B |Column C |New|
+---------+---------+---------+---+
|1210     |100      |200      |200|
|1300     |70       |50       |70 |
|1200     |10       |50       |50 |
|1310     |15       |300      |15 |
+---------+---------+---------+---+

这个方法直接在原DataFrame上添加新列,保留所有数据行,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:10:35