代码之家  ›  专栏  ›  技术社区  ›  Qubix

在pyspark数据帧中删除连续的重复项

  •  2
  • Qubix  · 技术社区  · 6 年前

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

    1 回复  |  直到 6 年前
        1
  •  4
  •   plalanne    6 年前

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

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