在星星之火-sql或电火花,我必须转换一个巴西货币浮点数。我在做:
data=[('bruce','wayne','1950-01-01','Male',9876543.21)]
columns=["NAME","LASTNAME","DOB","SEX","GOLD"]
df=spark.createDataFrame(data=data,schema=columns)
df= df \
.withColumn("GOLD_STRING",spf.concat(spf.lit("R$ "),
spf.when(spf.substring(df.GOLD.cast("string"),-21,3)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-21,3),spf.lit('.'))).otherwise(""),
spf.when(spf.substring(df.GOLD.cast("string"),-18,3)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-18,3),spf.lit('.'))).otherwise(""),
spf.when(spf.substring(df.GOLD.cast("string"),-15,3)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-15,3),spf.lit('.'))).otherwise(""),
spf.when(spf.substring(df.GOLD.cast("string"),-12,3)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-12,3),spf.lit('.'))).otherwise(""),
spf.when(spf.substring(df.GOLD.cast("string"),-9,3)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-9,3),spf.lit('.'))).otherwise(""),
spf.when(spf.substring(df.GOLD.cast("string"),-6,3)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-6,3),spf.lit(','))).otherwise(""),
spf.when(spf.substring(df.GOLD.cast("string"),-2,2)!="",spf.concat(spf.substring(df.GOLD.cast("string"),-2,3))).otherwise("00")))
df.show()结果我得到了:
+-----+--------+----------+----+----------+---------------+
| NAME|LASTNAME| DOB| SEX| GOLD| GOLD_STRING|
+-----+--------+----------+----+----------+---------------+
|bruce| wayne|1950-01-01|Male|9876543.21|R$ 9.876.543,21|
+-----+--------+----------+----+----------+---------------+这正是我所需要的,但有没有一种更简单的方法呢?提前感谢!任何帮助都将不胜感激!
发布于 2022-08-05 04:24:24
对于数字格式,format_number函数将以'#,###,###.##'格式打印这些数字。尽管这仍然需要使用多个replace替换千和十进制分隔符。
df = df.withColumn("GOLD_STRING", spf.expr("concat('R$ ', replace(replace(replace(format_number(GOLD, 2), '.', ';'), ',', '.'), ';', ','))"))
df.show()
+-----+--------+----------+----+----------+---------------+
| NAME|LASTNAME| DOB| SEX| GOLD| GOLD_STRING|
+-----+--------+----------+----+----------+---------------+
|bruce| wayne|1950-01-01|Male|9876543.21|R$ 9.876.543,21|
+-----+--------+----------+----+----------+---------------+https://stackoverflow.com/questions/73240390
复制相似问题