使用 PySpark 和 Babel 将浮点数格式化为货币

问题描述

我想使用 Babel 和 PySpark 将 float 转换为 currency

样本数据:

amount       currency
2129.9       RON
1700         EUR
1268         GBP
741.2        USD
142.08091153 EUR
4.7E7        USD
0            GBP

我试过了:

df = df.withColumn(F.col('amount'),format_currency(F.col('amount'),F.col('currency'),locale='be_BE'))

df = df.withColumn(F.col('amount'),'EUR',locale='be_BE'))

他们都给我一个错误

enter image description here

解决方法

预处理数据框的 amount 列时似乎存在问题。从错误中可以明显看出,转换为字符串后的 value 不仅仅是数字,它必须根据这个 table 并且还有一些额外的字符。您可以检查此列以查找并删除不必要的字符以解决此问题。例如:

>>> import decimal
>>> value = '10.0'
>>> value = decimal.Decimal(str(value))
>>> value
Decimal('10.0')
>>> value = '10.0e'
>>> value = decimal.Decimal(str(value))
Traceback (most recent call last):
  File "<pyshell#9>",line 1,in <module>
    value = decimal.Decimal(str(value))
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]   # as '10.0e' is not just numeric
,

要将 Python 库与 Spark 数据帧一起使用,您需要使用 UDF:

from babel.numbers import format_currency
import pyspark.sql.functions as F

format_currency_udf = F.udf(lambda a,c: format_currency(a,c))

df2 = df.withColumn(
    'amount',format_currency_udf('amount','currency')
)

df2.show()
+----------------+--------+
|          amount|currency|
+----------------+--------+
|     RON2,129.90|     RON|
|       €1,700.00|     EUR|
|       £1,268.00|     GBP|
|       US$741.20|     USD|
|         €142.08|     EUR|
|US$47,000,000.00|     USD|
+----------------+--------+