Pyspark 列转换具有正数和负数的字符串

Posted

技术标签:

【中文标题】Pyspark 列转换具有正数和负数的字符串【英文标题】:Pyspark column convert a string which has both positive and negative numbers 【发布时间】:2020-09-03 10:02:01 【问题描述】:

我有一个字符串数据类型的 pysapark 列。但它有正数和负数。如何将它们转换为数字。

总金额 = 交易量 * price_perunit 目前 Volume = String, price_perunit = double 预期输出:

Volume     price_perunit     total amount
-0.75      100                -75
  8        100                 800
 -0.01     8                   -0.08

现在,当我乘法时,我得到以下错误的结果,因为负号不再可用。

Volume     price_perunit     total amount
-0.75      100                75
  8        100                 800
 -0.01     8                   0.08

【问题讨论】:

【参考方案1】:

只是投射。

df.printSchema()
root
 |-- Volume: string (nullable = true)
 |-- price_perunit: double (nullable = true)


df.withColumn('Volume', col('Volume').cast('double')) \
  .withColumn('total amount', expr('Volume * price_perunit')) \
  .show()

+------+-------------+------------+
|Volume|price_perunit|total amount|
+------+-------------+------------+
| -0.75|          100|       -75.0|
|   8.0|          100|       800.0|
| -0.01|            8|       -0.08|
+------+-------------+------------+

【讨论】:

以上是关于Pyspark 列转换具有正数和负数的字符串的主要内容,如果未能解决你的问题,请参考以下文章