如何从sparkDataframe中的字符串列将数字字符识别为日期

x759pob2  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(229)

我想从sparkDataframe列中的字符串中提取数字字符。
例如

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 ?
vsdwdz23

vsdwdz231#

您应该首先通过regex\u 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   |
+---+--------+----+-----+

相关问题