问题描述
我有一个带美元符号的字符串列。如何转换为doubletype或float以便对它进行计算?
这些列看起来像是“ $ 1000,000.28”。
谢谢。
解决方法
您可以使用string.replace删除$符号,然后可以仅使用float()将字符串转换为float。
money = '$12,345'
money = money.replace('$','') .replace(',','') #this replaces the $ and,in the string
money = float(money)
,
使用regexp_replace
函数并将其强制转换为两倍。
import pyspark.sql.functions as f
df2 = df.withColumn('new_value',f.regexp_replace('value','[$,]','').cast('double'))
df2.printSchema()
df2.show(10,False)
root
|-- id: string (nullable = true)
|-- value: string (nullable = true)
|-- new_value: double (nullable = true)
+---+------------+----------+
|id |value |new_value |
+---+------------+----------+
|1 |$1000,000.28|1000000.28|
+---+------------+----------+