【问题标题】:Drop consecutive duplicates in a pyspark dataframe在 pyspark 数据框中删除连续重复项
【发布时间】:2018-09-04 18:20:40
【问题描述】:

有一个像这样的数据框:

## +---+---+
## | 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|
## +---+---+

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

【问题讨论】:

  • By 'consecutive' 我是按照一定的顺序来猜测的,比如num。这是正确的,还是您也希望这样的 id 分布像 [1,2,1,1,2] 导致 [1,2,1,2]
  • 顺序应该由ids给出,所以你的例子是正确的。 [1, 2, 1, 1, 2] 应该导致 [1, 2, 1, 2]。
  • spark 从数据源获取记录时会打乱记录,因此如果我必须提供行号,您将如何确保顺序意味着要引用哪一列

标签: apache-spark pyspark pyspark-sql


【解决方案1】:

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

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|
+---+---+

【讨论】:

    猜你喜欢
    • 2012-12-12
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2019-09-09
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多