【问题标题】:Pyspark column convert a string which has both positive and negative numbersPyspark 列转换具有正数和负数的字符串
【发布时间】: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

【问题讨论】:

    标签: dataframe pyspark casting


    【解决方案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|
    +------+-------------+------------+
    

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      相关资源
      最近更新 更多