如何在python数据框中为2列添加€符号前缀和后缀%符号

时间:2021-07-28 02:48:09

标签: python pyspark

我有一个数据框

enter image description here

并且我想将 € 符号和 % 符号添加到我的结果数据框中,其中有值而不是所有行。我的最终数据框是

enter image description here

这是我尝试过的:

df = lit(col('€'+'Currency'))
df= lit(col('Average'+'%'))

提前致谢

1 个答案:

答案 0 :(得分:0)

在 pyspark 中,它应该是简单的 when() else() 实现。 确保将列数据类型转换为 SrtingType() 而不是 DoubleType()。

from pyspark.sql import functions as F

# Sample Dataframe
data = [(None,"55.6"),("492.38",None)]
columns=["Currency","Average"]
df=spark.createDataFrame(data=data, schema=columns)

# Implementation
df = df.withColumn("Currency", F.when(df.Currency.isNotNull(), F.concat(F.lit("$"),df.Currency)).otherwise(df.Currency))\
  .withColumn("Average", F.when(df.Average.isNotNull(), F.concat(df.Average, F.lit("%"))).otherwise(df.Average))
df.show()

#+--------+-------+
#|Currency|Average|
#+--------+-------+
#|    null|  55.6%|
#| $492.38|   null|
#+--------+-------+
相关问题