[英]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
遍歷該行中的所有作者,這在行中不是恆定的。
我嘗試實現給PySpark DataFrames: filter where some value is in array column的解決方案,但它給了我
ValueError:某些類型無法通過前 100 行來確定,請采樣重試
有沒有簡潔的方法來實現這個過濾器?
您可以使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.