[英]How to drop duplicates from PySpark Dataframe and change the remaining column value to null
我是 Pyspark 的新手。 我有一個 Pyspark 數據框,我想根據 id 和時間戳列刪除重復項。 然后我想將重復 id 的讀取值替換為 null。 我不想使用熊貓。 請參閱以下內容:
數據框:
id reading timestamp
1 13015 2018-03-22 08:00:00.000
1 14550 2018-03-22 09:00:00.000
1 14570 2018-03-22 09:00:00.000
2 15700 2018-03-22 08:00:00.000
2 16700 2018-03-22 09:00:00.000
2 18000 2018-03-22 10:00:00.000
期望的輸出:
id reading timestamp
1 13015 2018-03-22 08:00:00.000
1 Null 2018-03-22 09:00:00.000
2 15700 2018-03-22 08:00:00.000
2 16700 2018-03-22 09:00:00.000
2 18000 2018-03-22 10:00:00.000
我需要如何添加到此代碼:
df.dropDuplicates(['id','timestamp'])
任何幫助將非常感激。 非常感謝
在 Scala 上可以通過分組來完成,並用 null 替換“讀取”值,其中計數大於 1:
val df = Seq(
(1, 13015, "2018-03-22 08:00:00.000"),
(1, 14550, "2018-03-22 09:00:00.000"),
(1, 14570, "2018-03-22 09:00:00.000"),
(2, 15700, "2018-03-22 08:00:00.000"),
(2, 16700, "2018-03-22 09:00:00.000"),
(2, 18000, "2018-03-22 10:00:00.000")
).toDF("id", "reading", "timestamp")
// action
df
.groupBy("id", "timestamp")
.agg(
min("reading").alias("reading"),
count("reading").alias("readingCount")
)
.withColumn("reading", when($"readingCount" > 1, null).otherwise($"reading"))
.drop("readingCount")
輸出是:
+---+-----------------------+-------+
|id |timestamp |reading|
+---+-----------------------+-------+
|2 |2018-03-22 09:00:00.000|16700 |
|1 |2018-03-22 08:00:00.000|13015 |
|1 |2018-03-22 09:00:00.000|null |
|2 |2018-03-22 10:00:00.000|18000 |
|2 |2018-03-22 08:00:00.000|15700 |
+---+-----------------------+-------+
猜猜,可以很容易地轉換為 Python。
使用 Window 函數計算分區id, timestamp
重復項的一種方法,然后根據計數更新reading
:
from pyspark.sql import Window
w = Window.partitionBy("id", "timestamp").orderBy("timestamp")
df.select(col("id"),
when(count("*").over(w) > lit(1), lit(None)).otherwise(col("reading")).alias("reading"),
col("timestamp")
) \
.dropDuplicates(["id", "reading", "timestamp"]).show(truncate=False)
或使用分組依據:
df.groupBy("id", "timestamp").agg(first("reading").alias("reading"), count("*").alias("cn")) \
.withColumn("reading", when(col("cn") > lit(1), lit(None)).otherwise(col("reading"))) \
.select(*df.columns) \
.show(truncate=False)
給出:
+---+-------+-----------------------+
|id |reading|timestamp |
+---+-------+-----------------------+
|1 |null |2018-03-22 09:00:00.000|
|1 |13015 |2018-03-22 08:00:00.000|
|2 |18000 |2018-03-22 10:00:00.000|
|2 |15700 |2018-03-22 08:00:00.000|
|2 |16700 |2018-03-22 09:00:00.000|
+---+-------+-----------------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.