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

需求:将Pandas中Lambda实现的default_flag1列逻辑转换为PySpark代码

Pandas转PySpark实现代码

原Pandas代码的逻辑是根据三个条件判断生成default_flag1列:当A等于1、crr属于('sss','tttt')、reg等于'T'这三个条件满足任意一个时,值为'T',否则为'F'。对应的PySpark实现如下:

from pyspark.sql.functions import when, col

Source_df_write = Source_df_write.withColumn(
    "default_flag1",
    when(
        (col("A") == 1) | (col("crr").isin("sss", "tttt")) | (col("reg") == "T"),
        "T"
    ).otherwise("F")
)

说明

  • 用withColumn添加新列,相比Pandas的行遍历apply,更适配PySpark的分布式计算模型,性能更优
  • 通过col()引用DataFrame列,用|表示逻辑或,isin()实现集合成员判断
  • when-otherwise结构对应原代码的三元表达式逻辑

内容的提问来源于stack exchange,提问作者Hala El Henawy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:02:02