You need to enable JavaScript to run this app. 如何在Python DataFrame的两列分别添加€前缀和%后缀
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python DataFrame的两列分别添加€前缀和%后缀

你原有代码的错误在于列引用和常量拼接的逻辑顺序错误,也没有对空值行做过滤,正确的PySpark实现方式如下:

首先导入需要用到的内置函数:

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

如果你的Currency、Average列已经是字符串类型,直接执行以下逻辑即可:

# 给非空的货币行添加€前缀
df = df.withColumn("Currency",
    when(col("Currency").isNotNull(), concat(lit("€"), col("Currency")))
    .otherwise(col("Currency"))
)

# 给非空的平均值行添加%后缀
df = df.withColumn("Average",
    when(col("Average").isNotNull(), concat(col("Average"), lit("%")))
    .otherwise(col("Average"))
)

如果两列是数值类型,需要先转成字符串再拼接避免类型报错,调整后代码如下:

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

df = df.withColumn("Currency",
    when(col("Currency").isNotNull(), concat(lit("€"), col("Currency").cast("string")))
    .otherwise(col("Currency"))
)

df = df.withColumn("Average",
    when(col("Average").isNotNull(), concat(col("Average").cast("string"), lit("%")))
    .otherwise(col("Average"))
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:09:01