【问题标题】:how to identify digital chars as date from a string column in spark dataframe如何从火花数据框中的字符串列中将数字字符识别为日期
【发布时间】:2020-11-14 14:27:14
【问题描述】:

我想从 spark 数据框列中的字符串中提取数字字符。

例如

   id    val (string)
   58    [dttg] 201805_mogtca_onvt
   91    20050221_frcas
   17    201709 dcsevas

我需要:

 id     a_date      year     month     
 58     201805      2018     05
 91     20050221    2005     02
 17     201709      2017     09  
 

我正在尝试:

 df.withColumn('date', DF.to_date(F.col('val').isdigit() # how to get digital chars ?

【问题讨论】:

    标签: scala dataframe apache-spark


    【解决方案1】:

    您应该首先通过 regex_replace 删除所有非数字字符:

    df.withColumn("a_date", regexp_replace($"val", "[^0-9]", ""))
    

    然后,由于您似乎在每一行中都有不同的时间格式,最简单的方法是使用子字符串

    df.withColumn("a_date", regexp_replace($"val", "[^0-9]", ""))
      .withColumn("year", substring($"a_date", 0, 4)) 
      .withColumn("month", substring($"a_date", 5, 2))
      .drop("val")
    

    输入

    +---+-------------------------+
    |id |val                      |
    +---+-------------------------+
    |58 |[dttg] 201805_mogtca_onvt|
    |91 |20050221_frcas           |
    |17 |201709 dcsevas           |
    +---+-------------------------+
    

    输出

    +---+--------+----+-----+
    |id |a_date  |year|month|
    +---+--------+----+-----+
    |58 |201805  |2018|05   |
    |91 |20050221|2005|02   |
    |17 |201709  |2017|09   |
    +---+--------+----+-----+
    

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      相关资源
      最近更新 更多