【问题标题】:Pyspark handle convert from string to decimalPyspark 句柄从字符串转换为十进制
【发布时间】:2021-12-10 19:57:42
【问题描述】:

我是 Databricks 中 Pyspark 的新手,所以这就是我在以下方面苦苦挣扎的原因: 我有一个数据框,其中包含数据类型为字符串的列。 一个示例(见下图)是 netto_resultaat 列。

要求是将此列和其他与财务相关的列从字符串更改为小数。这是因为我想在 Azure SQL 数据库中导出架构和数据。

我尝试了以下方法:

从 pyspark.sql.functions 导入 col 从 pyspark.sql.types 导入 DecimalType newouterjoindffinal = newouterjoindf.withColumn("netto_resultaat",col("netto_resultaat").cast(DecimalType())) newouterjoindffinal.printSchema()

结果是 netto_resultaat 列中的数字被转换为空。有些记录的数据为 -100,880 、 35,312,000 或 118,579,525。

有什么建议吗?

【问题讨论】:

    标签: string pyspark


    【解决方案1】:

    这是因为你的数字中有逗号,而你必须用点代替。

    from pyspark.sql import functions as F
    
    df = pd.DataFrame({"netto_resultaat": ["100,800", "10,20", "20,342"]})
    df = spark.createDataFrame(df)
    
    df.show()
    
    # output
    +---------------+
    |netto_resultaat|
    +---------------+
    |        100,800|
    |          10,20|
    |         20,342|
    +---------------+
    

    你必须先用点替换逗号,然后应用转换:

    (
        df
        .withColumn("netto_resultaat", 
                    F.regexp_replace("netto_resultaat", ",", ".")
                    .cast(DecimalType())
                   )
        .show()
    )
    
    # output
    +---------------+
    |netto_resultaat|
    +---------------+
    |            101|
    |             10|
    |             20|
    +---------------+
    

    如果有数千个,则替换为空字符串(我不完全了解您的情况):

    (
        df
        .withColumn("netto_resultaat", 
                    F.regexp_replace("netto_resultaat", ",", "")
                    .cast(DecimalType())
                   )
        .show()
    )
    
    # output
    +---------------+
    |netto_resultaat|
    +---------------+
    |         100800|
    |           1020|
    |          20342|
    

    【讨论】:

    • 我收到了一个带有描述的属性错误:未定义名称“F”。正则表达式前的“F”是什么意思?
    • from pyspark.sql import functions as F。我更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多