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

PySpark数据框条件赋值:将stat=1的Name字段设为toto

PySpark数据框条件更新字段解决方案

你可以使用PySpark的when和otherwise函数结合withColumn方法实现需求,具体代码如下:

完整实现代码

from pyspark.sql.functions import when, col
import pandas as pd

# 原始数据创建Spark数据框
data = [['tom', 1], ['nick', 1], ['juli', 2]]
pd_df = pd.DataFrame(data, columns=['Name', 'stat'])
df = spark.createDataFrame(pd_df)

# 执行条件转换
transformed_df = df.withColumn(
    "Name",
    when(col("stat") == 1, "toto").otherwise(col("Name"))
)

# 查看结果
transformed_df.show()

代码说明

  • withColumn("Name", ...):直接替换原有的Name字段(若要新增字段可修改第一个参数为新字段名)
  • when(col("stat") == 1, "toto"):指定判断条件,当stat等于1时将Name设为"toto"
  • otherwise(col("Name")):条件不满足时,保留Name字段的原始值

执行后transformed_df的输出结果为:

+-----+----+
| Name|stat|
+-----+----+
| toto|   1|
| toto|   1|
| juli|   2|
+-----+----+

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:25:53