【问题标题】:filter rows for column value in list of words pyspark在单词列表pyspark中过滤列值的行
【发布时间】:2021-04-12 02:36:18
【问题描述】:

我正在使用 pyspark 数据框。我有一个专栏words(array<string>)如下图:

+---+--------------------------------------------------------------------------------+
| id|                                                                           words|                      
----+--------------------------------------------------------------------------------+
|012|[content, type, multipart, alternative, boundaries, nextpart, nextpart, drama,..|
|013|[received, from, am5eur02ht120, eop, eur02, prod, protection, outlook by, pro...|
|014|[data, care, much, important, information, summer, care, send, faraway, forget..|

我还有一个单词列表:

list = ["protection", "content", "received"]

我想过滤列表中具有任何值的行。

预期输出:

+---+--------------------------------------------------------------------------------+
| id|                                                                           words|                      
----+--------------------------------------------------------------------------------+
|012|[content, type, multipart, alternative, boundaries, nextpart, nextpart, drama,..|
|013|[received, from, am5eur02ht120, eop, eur02, prod, protection, outlook by, pro...|

【问题讨论】:

    标签: python apache-spark pyspark


    【解决方案1】:

    我认为你可以使用array_intersect 函数和size 函数来实现你需要的东西,像这样(未经测试,不确定这个F.lit(list) 的确切代码):

    >>> import pyspark.sql.functions as F
    
    >>> df.show()
    +----------------+
    |           words|
    +----------------+
    |[content, word2]|
    |      [111, 222]|
    +----------------+
    
    >>> list_col = F.array(*[F.lit(cl) for cl in list])
    >>> df.filter(F.size(F.array_intersect(F.col("words"), list_col)) > 0).show()
    +----------------+
    |           words|
    +----------------+
    |[content, word2]|
    +----------------+
    

    【讨论】:

    • 感谢您的调查。上述解决方案抛出错误:Py4JJavaError: An error occurred while calling z:org.apache.spark.sql.functions.lit. : java.lang.RuntimeException: Unsupported literal type class java.util.ArrayList
    • 感谢您提供更新的解决方案。你能解释一下list_col = F.array(*[F.lit(cl) for cl in list]) 发生了什么吗?
    • array_intersect 函数需要两个数组作为参数。该行从给定值列表中创建数组
    猜你喜欢
    • 2018-03-24
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    相关资源
    最近更新 更多