【问题标题】:F.when(~F.col('text').like('\bfoo\b') not working as expected in PySparkF.when(~F.col('text').like('\bfoo\b') 在 PySpark 中没有按预期工作
【发布时间】:2021-06-23 01:31:11
【问题描述】:

为什么这部分(~F.col('text').rlike('\bfoo\b') 不起作用?

更新:

import pyspark.sql.functions as F
    
df = spark.createDataFrame(['Some text with foo and more text','Some text with bar and more text'],['value_1',None], "string").toDF("text", "check")
            
df_new = df.withColumn('check', F.when(((F.col('text').isNotNull()) & \
                                        (F.col('check').isNull() & \
                                        (~F.col('text').rlike('\bfoo\b')), 
                                my_udf(F.col('text'))) \
.otherwise(F.col('check'))
            
df_new.show(truncate=False)
+----------------------------------------+
|text                            |check  |
+--------------------------------+-------|
|Some text with foo and more text|value_1|
|Some text with bar and more text|       |
+--------------------------------+-------+

【问题讨论】:

    标签: python-3.x apache-spark pyspark apache-spark-sql


    【解决方案1】:

    尝试使用rlike 来代替使用正则表达式:

    df_new = df.withColumn('check', ~F.col('text').rlike(r'\bfoo\b'))
    
    df_new.show(truncate=False)
    #+--------------------------------+-----+
    #|text                            |check|
    #+--------------------------------+-----+
    #|Some text with foo and more text|false|
    #|Some text with bar and more text|true |
    #+--------------------------------+-----+
    

    而且这里不用whenrlike/like已经返回了一个布尔值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2015-09-05
      • 2014-01-26
      • 2018-08-30
      相关资源
      最近更新 更多