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

Filter PySpark DataFrame by checking if string appears in column

我是 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 遍历该行中的所有作者,这在各行中不是常量。

我尝试实施给 的解决方案,但它给了我

ValueError: Some of types cannot be determined by the first 100 rows, please try again with sampling

是否有实现此过滤器的简洁方法?

您可以使用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]|
+--------------------+

只是补充@Psidom 的精彩回答。
我知道你的列 author 是一个数组,但对于另一种类型的列(如字符串),你可以这样做:

df.filter(df.authors.contains('Some Author')).show()