python - 替换 PySpark 中的字符串

标签 python dataframe replace pyspark

我有一个数据框,其中包含欧洲格式的数字,我将其作为字符串导入。逗号作为十进制,反之亦然 -

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)

期望的输出: df.show()

+---------+
|  revenue|
+---------+
|-1269.75|
+---------+
df.printSchema()
root
 |-- revenue: float (nullable = true)

我正在使用函数 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|
+-------+
|       |
+-------+

最佳答案

您需要转义 . 以按字面匹配它,因为 .matches almost any character 的特殊字符在正则表达式中:

df = df.withColumn('revenue', regexp_replace(col('revenue'), "\\.", ""))

关于python - 替换 PySpark 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53088064/

相关文章:

python - Django - 格式化/访问模板中的 Pandas.to_dict() 数据框

regex - 戈朗 : Remove all characters except | from string

javascript - 在字符串中查找部分但替换整个大小写正则表达式?

python - 根据另一个数据框的匹配结果在数据框中创建新列

Python - 在 Pandas DataFrame 中取消嵌套单元格

javascript - 正则表达式用另一个字符替换每个字符,除了方括号中的内容

python - numpy数组:快速填充和提取数据

Python/Selenium - 如何切换 java 树菜单?

python - 如何使用 Python 3 在 requests.get() 请求期间抑制 http.client 异常日志记录

python - 将 json 数据集转换为 pandas 数据框