【问题标题】:Join 2 Dataframes with Regex in where clause pyspark在 where 子句 pyspark 中使用正则表达式加入 2 个数据框
【发布时间】:2021-05-07 22:43:24
【问题描述】:

我们有两个数据框

df = spark.createDataFrame([
        (1, 'Nick', 'Miller'),
        (2, 'Jessica', 'Day'),
        (3, 'Winston', 'Schmidt'),
       ], ['id', 'First_name', 'Last_name'])

df1 = spark.createDataFrame([ (1, '^[a-lA-L]', 'type1'), (3, '^[m-zM-Z]', 'type2')], ['id', 'regex_match', 'vaule']

需要加入这两个dataframe,其中df1.regex_match匹配df.Last_name

需要的输出如下:请有任何建议:

join df to df1 using left join

【问题讨论】:

    标签: regex dataframe apache-spark join pyspark


    【解决方案1】:

    您可以使用rlike 条件加入:

    import pyspark.sql.functions as F
    
    result = df.alias('df').join(
        df1.drop('id').alias('df1'),
        F.expr('df.Last_name rlike df1.regex_match'),
        'left'
    ).drop('regex_match')
    
    result.show()
    +---+----------+---------+-----+
    | id|First_name|Last_name|vaule|
    +---+----------+---------+-----+
    |  1|      Nick|   Miller|type2|
    |  2|   Jessica|      Day|type1|
    |  3|   Winston|  Schmidt|type2|
    +---+----------+---------+-----+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 2017-03-23
      相关资源
      最近更新 更多