我知道这只是一个非常简单的问题,很可能已经在某个地方得到了回答,但作为一个初学者,我仍然没有得到它并且正在寻找你的启示,请提前感谢你:
我有一个临时数据帧:
+----------------------------+---+
|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 |
Run Code Online (Sandbox Code Playgroud)
我需要的是删除主机列中的所有冗余项,换句话说,我需要获得最终的不同结果,如:
+----------------------------+---+
|host |day|
+----------------------------+---+
|in24.inetnebr.com |1 |
|uplherc.upl.com |1 |
|ix-esc-ca2-07.ix.netcom.com |1 |
|uplherc.upl.com |1 |
Run Code Online (Sandbox Code Playgroud)
小智 18
如果df是DataFrame的名称,则有两种方法可以获取唯一行:
df2 = df.distinct()
Run Code Online (Sandbox Code Playgroud)
要么
df2 = df.drop_duplicates()
Run Code Online (Sandbox Code Playgroud)
Aro*_*los 10
普通的distinct 不是那么用户友好,因为你不能设置列。在这种情况下,对你来说足够了:
df = df.distinct()
Run Code Online (Sandbox Code Playgroud)
但是如果日期列中有其他值,则不会从主机取回不同的元素:
+--------------------+---+
| 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|
+--------------------+---+
Run Code Online (Sandbox Code Playgroud)
在不同之后,您将返回如下:
df.distinct().show()
+--------------------+---+
| host|day|
+--------------------+---+
| in24.inetnebr.com| 1|
| uplherc.upl.com| 2|
| uplherc.upl.com| 1|
|ix-esc-ca2-07.ix....| 1|
+--------------------+---+
Run Code Online (Sandbox Code Playgroud)
因此你应该使用这个:
df = df.dropDuplicates(['host'])
Run Code Online (Sandbox Code Playgroud)
它将保留天的第一个值
如果您熟悉 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|
+--------------------+-----------------+
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15410 次 |
| 最近记录: |