首页 文章

通过检查字符串是否出现在列中来过滤PySpark DataFrame

提问于
浏览
1

我是Spark的新手并且正在玩过滤 . 我有一个通过读取json文件创建的pyspark.sql DataFrame . 架构的一部分如下所示:

root
 |-- authors: array (nullable = true)
 |    |-- element: string (containsNull = true)

我想过滤这个DataFrame,选择所有具有与特定作者相关的条目的行 . 因此,无论该作者是 authors 中列出的第一作者还是第n作者,如果出现其名称,则应包括该行 . 所以有些东西

df.filter(df['authors'].getItem(i)=='Some Author')

其中 i 遍历该行中的所有作者,这在行之间不是恒定的 .

我尝试实现给PySpark DataFrames: filter where some value is in array column的解决方案,但它给了我

ValueError:前100行无法确定某些类型,请再次尝试采样

有没有简洁的方法来实现这个过滤器?

1 回答

  • 5

    你可以使用 pyspark.sql.functions.array_contains 方法:

    df.filter(array_contains(df['authors'], 'Some Author'))
    

    from pyspark.sql.types import *
    from pyspark.sql.functions import array_contains
    
    lst = [(["author 1", "author 2"],), (["author 2"],) , (["author 1"],)]
    schema = StructType([StructField("authors", ArrayType(StringType()), True)])
    df = spark.createDataFrame(lst, schema)
    df.show()
    +--------------------+
    |             authors|
    +--------------------+
    |[author 1, author 2]|
    |          [author 2]|
    |          [author 1]|
    +--------------------+
    
    df.printSchema()
    root
     |-- authors: array (nullable = true)
     |    |-- element: string (containsNull = true)
    
    df.filter(array_contains(df.authors, "author 1")).show()
    +--------------------+
    |             authors|
    +--------------------+
    |[author 1, author 2]|
    |          [author 1]|
    +--------------------+
    

相关问题