如何使用spark中的窗口函数过滤数据

hba*_*bar 3 scala window-functions apache-spark spark-dataframe

我有以下数据:

rowid uid time code
   1  1      5    a
   2  1      6    b
   3  1      7    c
   4  2      8    a
   5  2      9    c
   6  2      9    c
   7  2     10    c
   8  2     11    a
   9  2     12    c
Run Code Online (Sandbox Code Playgroud)

现在我想以这样的方式过滤数据:我可以删除第6行和第7行,就像特定的uid一样,我希望在代码中只保留一行值为'c'的行

所以预期的数据应该是:

rowid uid time code
   1  1      5    a
   2  1      6    b
   3  1      7    c
   4  2      8    a
   5  2      9    c
   8  2     11    a
   9  2     12    c
Run Code Online (Sandbox Code Playgroud)

我正在使用这样的窗口函数:

val window = Window.partitionBy("uid").orderBy("time")
val change = ((lag("code", 1).over(window) <=> "c")).cast("int")
Run Code Online (Sandbox Code Playgroud)

这有助于我们用代码"c"识别每一行.我可以扩展它来过滤掉行以获得预期的数据

Dan*_*ula 5

如果你只想删除code ="c"的行(除了每个uid的第一行),你可以尝试以下方法:

val window = Window.partitionBy("uid", "code").orderBy("time")
val result = df
  .withColumn("rank", row_number().over(window))
  .where(
    (col("code") !== "c") ||
    col("rank") === 1
  )
  .drop("rank")
Run Code Online (Sandbox Code Playgroud)

根据新信息进行编辑:

val window = Window.partitionBy("uid").orderBy("time")
val result = df
  .withColumn("lagValue", coalesce(lag(col("code"), 1).over(window), lit("")))
  .where(
    (col("code") !== "c") ||
    (col("lagValue") !== "c")
  )
  .drop("lagValue")
Run Code Online (Sandbox Code Playgroud)