【问题标题】:pyspark dataframe: remove duplicates in an array columnpyspark 数据框:删除数组列中的重复项
【发布时间】:2021-01-01 19:20:16
【问题描述】:

我想删除 pyspark 数据框列中的一些重复单词。

基于Remove duplicates from PySpark array column

我的火花:

  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”无法过滤掉它们?

谢谢

【问题讨论】:

  • 请查看给定的链接。可能会有所帮助:stackoverflow.com/questions/47316783/…
  • and 在字符串中的任何位置都不重复。那么基于什么你想删除它?还是您的意思是bookthis?你能展示你想要的最终结果吗?
  • 它不会过滤掉任何东西,因为它只是一个由单个字符串而不是多个字符串组成的数组,所以 array_distinct 只是在数组中找到一个字符串。我假设您需要从字符串中删除重复的单词,而不是从字符串数组中删除。这是正确的吗?
  • @user3448022,您尝试过我的回答是否有帮助?

标签: python dataframe apache-spark pyspark


【解决方案1】:

您可以使用来自 pyspark sql.functionslcasesplitarray_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,' ') 在空格上拆分数组,这会产生

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

然后你将它传递给array_distinct,它会产生

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

最后,使用array_join加入空格

i like this book and be downloaded on line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多