【问题标题】:Removing alphabets from alphanumeric values present in column of dataframe of spark从火花数据框列中存在的字母数字值中删除字母
【发布时间】:2020-08-19 05:15:28
【问题描述】:

两列数据框的样子。

SKU   | COMPSKU

PT25M | PT10M
PT3H  | PT20M
TH    | QR12
S18M  | JH

scala 的火花

如何删除所有字母而只保留数字..

预期输出:

25|10
3|20
0|12
18|0

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    你也可以这样做。

    df.withColumn(
        "SKU",
        when(regexp_replace(col("SKU"),"[a-zA-Z]","")==="",0
            ).otherwise(regexp_replace(col("SKU"),"[a-zA-Z]","")) 
    ).withColumn(
        "COMPSKU",
        when(regexp_replace(col("COMPSKU"),"[a-zA-Z]","")==="", 0
            ).otherwise(regexp_replace(col("COMPSKU"),"[a-zA-Z]",""))
    ).show()
    /*
            +-----+-------+
            |  SKU|COMPSKU|
            +-----+-------+
            |  25 |  10   |
            |   3 |  20   |
            |   0 |  12   |
            |  18 |   0   |
            +-----+-------+
    */
    

    【讨论】:

      【解决方案2】:

      尝试使用 regexp_replace 函数,然后使用 case when otherwise statement 将空值替换为 0。

      Example:

      df.show()
      /*
      +-----+-------+
      |  SKU|COMPSKU|
      +-----+-------+
      |PT25M|  PT10M|
      | PT3H|  PT20M|
      |   TH|   QR12|
      | S18M|     JH|
      +-----+-------+
      */
      
      df.withColumn("SKU",regexp_replace(col("SKU"),"[a-zA-Z]","")).
      withColumn("COMPSKU",regexp_replace(col("COMPSKU"),"[a-zA-Z]","")).
      withColumn("SKU",when(length(trim(col("SKU")))===0,lit(0)).otherwise(col("SKU"))).
      withColumn("COMPSKU",when(length(trim(col("COMPSKU")))===0,lit(0)).otherwise(col("COMPSKU"))).
      show()
      
      /*
      +---+-------+
      |SKU|COMPSKU|
      +---+-------+
      | 25|     10|
      |  3|     20|
      |  0|     12|
      | 18|      0|
      +---+-------+
      */
      

      【讨论】:

      • 导入import org.apache.spark.sql.functions._函数!
      猜你喜欢
      • 2017-11-25
      • 2012-11-15
      • 1970-01-01
      • 2019-12-28
      • 2021-05-17
      • 1970-01-01
      • 2022-09-23
      • 2018-02-24
      相关资源
      最近更新 更多