【问题标题】:How to get distinct rows in dataframe using pyspark?如何使用 pyspark 在数据框中获取不同的行?
【发布时间】:2016-12-03 15:19:12
【问题描述】:

我知道这只是一个非常简单的问题,很可能已经在某个地方得到了回答,但是作为一个初学者,我仍然不明白,正在寻求您的启发,提前谢谢您:

我有一个临时数据框:

+----------------------------+---+
|host                        |day|
+----------------------------+---+
|in24.inetnebr.com           |1  |
|uplherc.upl.com             |1  |
|uplherc.upl.com             |1  |
|uplherc.upl.com             |1  |
|uplherc.upl.com             |1  |
|ix-esc-ca2-07.ix.netcom.com |1  |
|uplherc.upl.com             |1  |

我需要的是删除主机列中的所有冗余项,换句话说,我需要得到最终的不同结果,例如:

+----------------------------+---+
|host                        |day|
+----------------------------+---+
|in24.inetnebr.com           |1  |
|uplherc.upl.com             |1  |
|ix-esc-ca2-07.ix.netcom.com |1  |
|uplherc.upl.com             |1  |

【问题讨论】:

    标签: distinct pyspark


    【解决方案1】:

    如果 df 是您的 DataFrame 的名称,则有两种方法可以获取唯一行:

    df2 = df.distinct()
    

    df2 = df.drop_duplicates()
    

    【讨论】:

    • 谢谢。这很简单
    【解决方案2】:

    正常的 distinct 对用户不太友好,因为您无法设置列。 在这种情况下,对你来说已经足够了:

    df = df.distinct()
    

    但如果您在日期列中有其他值,您将无法从主机中取回不同的元素:

    +--------------------+---+
    |                host|day|
    +--------------------+---+
    |   in24.inetnebr.com|  1|
    |     uplherc.upl.com|  1|
    |     uplherc.upl.com|  2|
    |     uplherc.upl.com|  1|
    |     uplherc.upl.com|  1|
    |ix-esc-ca2-07.ix....|  1|
    |     uplherc.upl.com|  1|
    +--------------------+---+
    

    distinct后你会得到如下结果:

    df.distinct().show()
    
    +--------------------+---+
    |                host|day|
    +--------------------+---+
    |   in24.inetnebr.com|  1|
    |     uplherc.upl.com|  2|
    |     uplherc.upl.com|  1|
    |ix-esc-ca2-07.ix....|  1|
    +--------------------+---+
    

    因此你应该使用这个:

    df = df.dropDuplicates(['host'])
    

    它将保留第一个值

    如果您熟悉 SQL 语言,它也适合您:

    df.createOrReplaceTempView("temp_table")
    new_df = spark.sql("select first(host), first(day) from temp_table GROUP BY host")
    
     +--------------------+-----------------+
    |  first(host, false)|first(day, false)|
    +--------------------+-----------------+
    |   in24.inetnebr.com|                1|
    |ix-esc-ca2-07.ix....|                1|
    |     uplherc.upl.com|                1|
    +--------------------+-----------------+
    

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多