代码之家  ›  专栏  ›  技术社区  ›  Thomas

从pyspark数组列中删除重复项

  •  1
  • Thomas  · 技术社区  · 7 年前

    我有一个pyspark数据帧,其中包含 ArrayType(StringType()) 列。此列包含数组中需要删除的重复字符串。例如,一行条目可能看起来像 [milk, bread, milk, toast] . 假设我的数据帧是命名的 df 我的专栏名为 arraycol . 我需要这样的东西:

    df = df.withColumn("arraycol_without_dupes", F.remove_dupes_from_array("arraycol"))
    

    我的直觉是存在一个简单的解决方案,但是在浏览stackoverflow 15分钟后,我发现没有什么比分解列、删除完整数据框上的重复项、然后再次分组更好的方法了。有 得到了 做一个我没想到的简单方法,对吧?

    我使用的是Spark版本“2.3.1”。

    1 回复  |  直到 7 年前
        1
  •  3
  •   pault Tanjin    7 年前

    对于pyspark 2.4+版,您可以使用 pyspark.sql.functions.array_distinct :

    from pyspark.sql.functions import array_distinct
    df = df.withColumn("arraycol_without_dupes", array_distinct("arraycol"))
    

    对于旧版本,您 可以 使用API函数 explode + groupBy collect_set 但A udf 这里的效率可能更高:

    from pyspark.sql.functions import udf
    
    remove_dupes_from_array = udf(lambda row: list(set(row)), ArrayType(StringType()))
    df = df.withColumn("arraycol_without_dupes", remove_dupes_from_array("arraycol"))
    
    推荐文章