繁体   English   中英

使用 pyspark 中的正则表达式将数字添加到字符串中最后一个字符之前的字符串

[英]Add number to a string before the last character in the string using regex in pyspark

我需要使用pyspark在字符串中的最后一个字符(即火花数据帧的列中)之前添加相同的数字。 例如,假设我有字符串2020_week42021_week5 我需要在 4 和 5 前面添加一个零,如下所示: 2020_week042021_week05 更大的背景是替换是有条件的 - 仅适用于个位数的周。 所以类似于:

df.withColumn('week', when(len(col("week")) == 10, regexp_replace(week, REGEX_PATTERN, "0")).otherwise(col("week")))

需要注意的是,对于需要替换的单个数字字符串, week列的长度始终为 10 个字符。

根据@thefourthbird 关于正则表达式的建议,我尝试了以下方法:

df1.withColumn('week', when(len(col("week")) == 10, regexp_replace(week, "^\d{4}_week(?=\d$)", "$00")).otherwise(col("week")))

我得到的错误与正则表达式本身无关,而是如何在 pyspark 中实现正则表达式。 错误:

TypeError: object of type 'Column' has no len()

我也试过:

import pyspark.sql.functions as F

df1.withColumn('week', when(F.length("week") == 10, regexp_replace(week, "^\d{4}_week(?=\d$)", "$00")).otherwise(col("week")))

错误:

NameError: name 'week' is not defined

更新:

df10.withColumn('week', when(length(col('week')) == 10, regexp_replace("week", "(?<=k)(?=\d$)", "0")).otherwise(col("week")))

您可以使用适用于任何字符串的substringconcat函数(无需使用正则表达式):

from pyspark.sql import functions as F


df = spark.createDataFrame([("2020_week4",), ("2021_week5",)], ["value"])

df.withColumn(
    "value",
    F.concat(
        F.expr("substring(value, 1, length(value)-1)"),
        F.lit('0'),
        F.substring("value", -1, 1)
    )
).show()

#+-----------+
#|      value|
#+-----------+
#|2020_week04|
#|2021_week05|
#+-----------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM