【问题标题】:How to efficiently check if a list of words is contained in a Spark Dataframe?如何有效地检查 Spark Dataframe 中是否包含单词列表?
【发布时间】:2018-07-29 21:50:10
【问题描述】:

使用 PySpark 数据帧,我正在尝试尽可能高效地执行以下操作。我有一个数据框,其中有一列包含文本和我想要过滤行的单词列表。所以:

数据框看起来像这样

df:
col1    col2   col_with_text
a       b      foo is tasty
12      34     blah blahhh
yeh     0      bar of yums

列表将是list = [foo,bar] 因此结果将是:

result:
col1    col2   col_with_text
a       b      foo
yeh     0      bar

之后不仅会进行相同的字符串匹配,还会使用 SequenceMatcher 左右测试相似性。这是我已经尝试过的:

def check_keywords(x):
   words_list = ['foo','bar']

   for word in x
       if word == words_list[0] or word == words_list[1]:
           return x

result = df.map(lambda x: check_keywords(x)).collect()

不幸的是,我没有成功,有人可以帮助我吗? 提前致谢。

【问题讨论】:

标签: python apache-spark dataframe pyspark


【解决方案1】:

您应该考虑使用 pyspark sql 模块函数而不是编写 UDF,有几个基于 regexp 的函数:

首先让我们从一个更完整的示例数据框开始:

df = sc.parallelize([["a","b","foo is tasty"],["12","34","blah blahhh"],["yeh","0","bar of yums"], 
                     ['haha', '1', 'foobar none'], ['hehe', '2', 'something bar else']])\
    .toDF(["col1","col2","col_with_text"])

如果要根据是否包含words_list 中的单词之一来过滤行,可以使用rlike

import pyspark.sql.functions as psf
words_list = ['foo','bar']
df.filter(psf.col('col_with_text').rlike('(^|\s)(' + '|'.join(words_list) + ')(\s|$)')).show()

    +----+----+------------------+
    |col1|col2|     col_with_text|
    +----+----+------------------+
    |   a|   b|      foo is tasty|
    | yeh|   0|       bar of yums|
    |hehe|   2|something bar else|
    +----+----+------------------+

如果要提取匹配正则表达式的字符串,可以使用regexp_extract

df.withColumn(
        'extracted_word', 
        psf.regexp_extract('col_with_text', '(?=^|\s)(' + '|'.join(words_list) + ')(?=\s|$)', 0))\
    .show()

    +----+----+------------------+--------------+
    |col1|col2|     col_with_text|extracted_word|
    +----+----+------------------+--------------+
    |   a|   b|      foo is tasty|           foo|
    |  12|  34|       blah blahhh|              |
    | yeh|   0|       bar of yums|           bar|
    |haha|   1|       foobar none|              |
    |hehe|   2|something bar else|              |
    +----+----+------------------+--------------+

【讨论】:

  • 嗨,你为什么在你的正则表达式中使用前瞻?
【解决方案2】:

好吧,我已经尝试过了,如果您更改单词列表。

words_list = ['foo', 'is', 'bar']

结果保持不变,不显示其他单词。

+----+----+------------------+--------------+ |col1|col2| col_with_text|extracted_word| +----+----+------------------+--------------+ | a| b| foo is tasty| foo| | 12| 34| blah blahhh| | | yeh| 0| bar of yums| bar| |haha| 1| foobar none| | |hehe| 2|something bar else| | +----+----+------------------+--------------+

【讨论】:

    猜你喜欢
    • 2012-06-17
    • 2018-04-21
    • 2023-02-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多