【问题标题】:Spark SQL DataFrame - distinct() vs dropDuplicates()Spark SQL DataFrame - distinct() 与 dropDuplicates()
【发布时间】:2016-06-10 13:39:00
【问题描述】:

我正在查看 DataFrame API,我可以看到两种不同的方法执行相同的功能来从数据集中删除重复项。

我可以理解 dropDuplicates(colNames) 将仅考虑列的子集来删除重复项。

这两种方法还有其他区别吗?

【问题讨论】:

    标签: scala apache-spark pyspark apache-spark-sql


    【解决方案1】:

    主要区别在于对列子集的考虑,这很棒! 使用 distinct 时,您需要事先 .select 选择要应用重复的列,并且返回的 Dataframe 仅包含这些选定的列,而 dropDuplicates(colNames) 将在删除重复的行后返回初始数据帧的所有列按照列。

    【讨论】:

      【解决方案2】:

      假设我们有以下 spark 数据帧

      +---+------+---+                                                                
      | id|  name|age|
      +---+------+---+
      |  1|Andrew| 25|
      |  1|Andrew| 25|
      |  1|Andrew| 26|
      |  2| Maria| 30|
      +---+------+---+
      

      distinct() 不接受任何参数,这意味着您无法选择删除重复项时需要考虑哪些列。这意味着考虑到数据框的所有列,以下命令将删除重复记录:

      df.distinct().show()
      
      +---+------+---+
      | id|  name|age|
      +---+------+---+
      |  1|Andrew| 26|
      |  2| Maria| 30|
      |  1|Andrew| 25|
      +---+------+---+
      

      现在,如果您想删除重复项,只考虑idname,您必须在distinct() 之前运行select()。例如,

      >>> df.select(['id', 'name']).distinct().show()
      +---+------+
      | id|  name|
      +---+------+
      |  2| Maria|
      |  1|Andrew|
      +---+------+
      

      但如果您只想将重复项删除到上述列的子集上但保留所有列,那么distinct() 不是您的朋友。


      dropDuplicates() 将删除在提供的列集上检测到的重复项,但它也会返回原始数据框中出现的所有列。

      df.dropDuplicates().show()
      
      +---+------+---+
      | id|  name|age|
      +---+------+---+
      |  1|Andrew| 26|
      |  2| Maria| 30|
      |  1|Andrew| 25|
      +---+------+---+
      

      dropDuplicates() 因此更适合当您想将重复项放在选定的列子集上,但又想保留所有列时:

      df.dropDuplicates(['id', 'name']).show()
      
      +---+------+---+
      | id|  name|age|
      +---+------+---+
      |  2| Maria| 30|
      |  1|Andrew| 25|
      +---+------+---+
      

      更多详情参考文章distinct() vs dropDuplicates() in Python

      【讨论】:

        【解决方案3】:

        javadoc,distinc() 和 dropDuplicates() 没有区别。

        删除重复项

        公共数据帧 dropDuplicates()

        返回一个新的 DataFrame,其中仅包含来自此的唯一行 数据框。这是 distinct 的别名。

        dropDuplicates() 是在 1.4 中作为 distinct() 的替代品引入的,因为您可以使用它的重载方法根据列的子集获取唯一行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-29
          相关资源
          最近更新 更多