gpt4 book ai didi

apache-spark - 在 pyspark 数据框中删除连续的重复项

转载 作者:行者123 更新时间:2023-12-04 05:01:00 30 4
gpt4 key购买 nike

有一个数据框,如:

## +---+---+
## | id|num|
## +---+---+
## | 2|3.0|
## | 3|6.0|
## | 3|2.0|
## | 3|1.0|
## | 2|9.0|
## | 4|7.0|
## +---+---+

我想删除连续的重复,并获得:
## +---+---+
## | id|num|
## +---+---+
## | 2|3.0|
## | 3|6.0|
## | 2|9.0|
## | 4|7.0|
## +---+---+

我找到了 ways of doing this在 Pandas 中,但在 Pyspark 中没有。

最佳答案

答案应该如您所愿,但可能有一些优化空间:

from pyspark.sql.window import Window as W
test_df = spark.createDataFrame([
(2,3.0),(3,6.0),(3,2.0),(3,1.0),(2,9.0),(4,7.0)
], ("id", "num"))
test_df = test_df.withColumn("idx", monotonically_increasing_id()) # create temporary ID because window needs an ordered structure
w = W.orderBy("idx")
get_last= when(lag("id", 1).over(w) == col("id"), False).otherwise(True) # check if the previous row contains the same id

test_df.withColumn("changed",get_last).filter(col("changed")).select("id","num").show() # only select the rows with a changed ID

输出:

+---+---+
| id|num|
+---+---+
| 2|3.0|
| 3|6.0|
| 2|9.0|
| 4|7.0|
+---+---+

关于apache-spark - 在 pyspark 数据框中删除连续的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52146821/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com