如何使用 Pyspark 将字符串列转换为小数列

How to Convert a String Column to Decimal Column using Pyspark

我有一个包含字符串列的数据框,我需要将其转换为十进制。这是数据示例:

我尝试了以下操作:

df_line_items = df_line_items.withColumn("product_sold_price", df_line_items.product_sold_price.cast("decimal(3,2)"))

,但它只是使所有值都为空。感谢任何想法。谢谢

那是因为decimal(3,2)只能允许3位精度和小数点后2位(范围-9.99到9.99),而你的数据超出了这个范围。从上图中,至少你需要将它们转换为 decimal(5,2).

不要使用小数,尝试使用双精度 - 这应该可以解决您的所有问题。

df_line_items = df_line_items.withColumn("product_sold_price", df_line_items.product_sold_price.cast("双"))