【问题标题】:convert string column to double with period as decimal point and thousands separator将字符串列转换为双精度,以句点作为小数点和千位分隔符
【发布时间】:2018-10-26 09:19:25
【问题描述】:

我正在编写一个程序来修复数据库列值(CSV 输入),其中包含从各种数据源连接的数字。

问题是它们有千位分隔符和小数分隔符,使用点“。”

例如:

  • 100.000.000 --> 10000000
  • 9.000 --> 9000
  • 0.600000 --> 0.6(十进制)
  • 12.000.000 --> 12000000
  • 0.200000 --> 0.2(十进制)
  • 1.000 --> 1000
  • 700.000 --> 700000

我尝试过使用条件正则表达式,但没有找到正确的方法,所以我必须分两个阶段进行(“何时”和正则表达式提取):

import sys
from pyspark import SQLContext, SparkContext
from pyspark.sql.types import StructType,StructField,StringType,DateType,IntegerType
sc = SparkContext()
sqlContext = SQLContext(sc)

from pyspark.sql.functions import regexp_replace, regexp_extract, col, when
df3 = sqlContext.createDataFrame([["100.000.000"],["9.000"],["0.600000"],["12.000.000"],["0.200000"],["1.000"],["700.000"]],["SENSOR_VALUE"])

df3.show()

regexDotDig6 = "\.(\d\d\d\d\d\d)";
regexDotDig3 = "\.(\d\d\d)";

df3 = df3.withColumn("SENSOR_VALUE", when(regexp_extract(df3.SENSOR_VALUE, regexDotDig6,1) == "",                                    regexp_replace(df3.SENSOR_VALUE, regexDotDig3, "$1"))                                    .otherwise(df3.SENSOR_VALUE).cast('double'))

df3.show()

有没有办法用相同的正则表达式或更有效的方式?

【问题讨论】:

    标签: python regex pyspark anaconda jupyter


    【解决方案1】:

    您可以使用pyspark.sql.Column.startswith 来检查字符串是否以"0" 开头。如果是,请将其转换为 double。如果不是,则将句点替换为空字符串,然后进行强制转换。

    from pyspark.sql.functions import col, when, regexp_replace
    
    df3.withColumn(
        "SENSOR_VALUE",
        when(
            col("SENSOR_VALUE").startswith("0"),
            col("SENSOR_VALUE")
        ).otherwise(regexp_replace("SENSOR_VALUE", "\.", "")).cast("double")
    ).show()
    #+------------+
    #|SENSOR_VALUE|
    #+------------+
    #|       1.0E8|
    #|      9000.0|
    #|         0.6|
    #|       1.2E7|
    #|         0.2|
    #|      1000.0|
    #|    700000.0|
    #+------------+
    

    【讨论】:

      【解决方案2】:

      这不是我设法的最佳解决方案...

      from pyspark.sql.functions import when, regexp_extract, regexp_replace
      
      df3 = df3.withColumn(
          "SENSOR_VALUE",
          when(
              regexp_extract(df3.SENSOR_VALUE, regexDotDig6,1) == "",
              regexp_replace(df3.SENSOR_VALUE, regexDotDig3, "$1")
          ).otherwise(df3.SENSOR_VALUE).cast('double'))
      
      df3.show()
      
      +------------+
      |SENSOR_VALUE|
      +------------+
      |       1.0E8|
      |      9000.0|
      |         0.6|
      |       1.2E7|
      |         0.2|
      |      1000.0|
      |    700000.0|
      +------------+
      

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2014-11-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多