替换PySp中的字符串

2024-05-28 20:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,有欧洲格式的数字,我把它作为字符串导入。逗号为十进制,反之亦然-

from pyspark.sql.functions import regexp_replace,col
from pyspark.sql.types import FloatType
df = spark.createDataFrame([('-1.269,75',)], ['revenue'])
df.show()
+---------+
|  revenue|
+---------+
|-1.269,75|
+---------+
df.printSchema()
root
 |-- revenue: string (nullable = true)

所需输出: 测向显示()

^{pr2}$

我使用函数regexp_replace首先将点替换为空格-然后将逗号替换为空点,最后转换为floatType。在

df = df.withColumn('revenue', regexp_replace(col('revenue'), ".", ""))
df = df.withColumn('revenue', regexp_replace(col('revenue'), ",", "."))
df = df.withColumn('revenue', df['revenue'].cast("float"))

但是,当我尝试替换下面的内容时,我得到了空字符串。为什么?我在等-1269,75。在

df = df.withColumn('revenue', regexp_replace(col('revenue'), ".", ""))
+-------+
|revenue|
+-------+
|       |
+-------+

Tags: 数据字符串fromimportdfsql格式数字

热门问题