如何在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
相关产品推荐
相关产品推荐

