【问题标题】:Check if a PySpark column matches regex and create new column based on results检查 PySpark 列是否与正则表达式匹配并根据结果创建新列
【发布时间】:2021-02-24 16:44:23
【问题描述】:

我有一个 PySpark 数据框,如下所示:

df:
+----+--------------------+
|  ID|               Email|
+----+--------------------+
|2345|  sample@example.org|
|2398| sample2@example.org|
|2328|   sampleexample.org|
|3983|   sample@exampleorg|
+----+--------------------+

我想将正则表达式应用于上述数据框(电子邮件列)并根据匹配结果(真或假)添加一个新列。我的正则表达式:

regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' 

基本上检查它是否是有效的电子邮件。所需的输出是:

df2:
+----+--------------------+--------+
|  ID|               Email| Matched|
+----+--------------------+--------+
|2345|  sample@example.org|    True|
|2398| sample2@example.org|    True|
|2328|   sampleexample.org|   False|
|3983|   sample@exampleorg|   False|
+----+--------------------+--------+

我只知道数据框filter 会删除那些与模式不匹配且不是预期结果的数据框。我还考虑过将该正则表达式用作函数并将其应用于电子邮件列,并执行以下操作:

def check(email):  
    if(re.search(regex, email)):  
        return True
    else:  
        return False
udf_check_email = udf(check, BooleanType())
df.withColumn('matched', udf_check_email(df.email)).show()

但我不确定这是否是最有效的方法。

【问题讨论】:

    标签: python regex apache-spark pyspark-dataframes


    【解决方案1】:

    我们可以使用SQL rlike函数作为,

    df = df.withColumn('matched',F.when(df.email.rlike('^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'),True).otherwise(False))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-16
      • 2023-03-10
      • 1970-01-01
      • 2016-11-10
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多