簡體   English   中英

pyspark 數據框:刪除數組列中的重復項

[英]pyspark dataframe: remove duplicates in an array column

我想刪除 pyspark 數據幀列中的一些重復單詞。

基於從 PySpark 數組列中刪除重復項

我的火花:

  2.4.5

py3代碼:

  test_df = spark.createDataFrame([("I like this Book and this book be DOWNLOADED on line",)], ["text"])
  t3 = test_df.withColumn("text", F.array("text")) # have to convert it to array because the original large df is array type.

  t4 = t3.withColumn('text', F.expr("transform(text, x -> lower(x))"))
  t5 = t4.withColumn('text', F.array_distinct("text"))
  t5.show(1, 120)

但得到

 +--------------------------------------------------------+
 |                                                    text| 
 +--------------------------------------------------------+
 |[i like this book and this book be downloaded on line]|
 +--------------------------------------------------------+

我需要刪除

 book and this

似乎“array_distinct”無法過濾掉它們?

謝謝

您可以使用 pyspark sql.functions lcasesplitarray_distinctarray_join函數

例如, F.expr("array_join(array_distinct(split(lcase(text),' ')),' ')")

這是工作代碼

import pyspark.sql.functions as F
df
.withColumn("text_new",
   F.expr("array_join(array_distinct(split(lcase(text),' ')),' ')")) \
.show(truncate=False)

說明:

在這里,您首先使用lcase(text)將所有內容轉換為小寫,然后使用split(text,' ')在空格上split(text,' ')數組,這會產生

[i, like, this, book, and, this, book, be, downloaded, on, line]|

然后你把它傳遞給array_distinct ,它產生

[i, like, this, book, and, be, downloaded, on, line]

最后,使用array_join將其與空格array_join

i like this book and be downloaded on line

暫無
暫無

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

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