簡體   English   中英

如何使用pyspark查找一列的字符串句子中是否包含一個或多個單詞

[英]How to use pyspark to find whether a column contains one or more words in it's string sentence

我有一個看起來像這樣的數據集

在此處輸入圖片說明

我正在嘗試使用 pyspark 從我的列表中標記或過濾包含單詞的行

參考列表看起來像 ['house','tree']

所以基本上它應該返回第一行和第三行。 它應該返回第二行,因為 tree 的末尾拼寫為 s。 我只想要全字匹配。

我的想法是字符串拆分字符串列,遍歷引用列表,有沒有更好的方法?

這對您來說可能是一個array_contains()解決方案 - 使用高階函數array_contains()而不是循環遍歷每個項目,但是為了實現該解決方案,我們需要稍微簡化一下。 例如需要將字符串列作為數組

在這里創建數據幀

from pyspark.sql import functions as F
from pyspark.sql import types as T
df = spark.createDataFrame([(1,"This is a Horse"),(2,"Monkey Loves trees"),(3,"House has a tree"),(4,"The Ocean is Cold")],[ "col1","col2"])
df.show(truncate=False)

輸出

+----+-----------------+
|col1|col2             |
+----+-----------------+
|1   |This is a Horse  |
|2   |Monkey Loves trees|
|3   |House has a tree |
|4   |The Ocean is Cold|
+----+-----------------+

此處的邏輯 - 使用 split() 將字符串列轉換為 ArrayType

df = df.withColumn("col2", F.split("col2", " "))
df = df.withColumn("array_filter", F.when(F.array_contains("col2", "This"), True).when(F.array_contains("col2", "tree"), True))
df = df.filter(F.col("array_filter") == True)
df.show(truncate=False)

輸出

   +----+---------------------+------------+
|col1|col2                 |array_filter|
+----+---------------------+------------+
|1   |[This, is, a, Horse] |true        |
|3   |[House, has, a, tree]|true        |
+----+---------------------+------------+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM