問題

使用Apache Spark解決問題的最佳方法是什麼?

我的資料集如下 –

 ID, DATE,       TIME, VALUE
001,2019-01-01, 0010, 150
001,2019-01-01, 0020, 150
001,2019-01-01, 0030, 160
001,2019-01-01, 0040, 160
001,2019-01-01, 0050, 150
002,2019-01-01, 0010, 151
002,2019-01-01, 0020, 151
002,2019-01-01, 0030, 161
002,2019-01-01, 0040, 162
002,2019-01-01, 0051, 152
 

當為每個ID更改’VALUE’時,我需要保留行.

我的預期輸出 –

 ID, DATE,       TIME, VALUE
001,2019-01-01, 0010, 150
001,2019-01-01, 0030, 160
001,2019-01-01, 0050, 150
002,2019-01-01, 0010, 151
002,2019-01-01, 0030, 161
002,2019-01-01, 0040, 162
002,2019-01-01, 0051, 152
 

  最佳答案

您可以使用lag函式與Window:

 val df = Seq(
  ("001", "2019-01-01", "0010", "150"),
  ("001", "2019-01-01", "0020", "150"),
  ("001", "2019-01-01", "0030", "160"),
  ("001", "2019-01-01", "0040", "160"),
  ("001", "2019-01-01", "0050", "150"),
  ("002", "2019-01-01", "0010", "151"),
  ("002", "2019-01-01", "0020", "151"),
  ("002", "2019-01-01", "0030", "161"),
  ("002", "2019-01-01", "0040", "162"),
  ("002", "2019-01-01", "0051", "152")
).toDF("ID", "DATE", "TIME", "VALUE")


df
  .withColumn("change",coalesce($"VALUE"=!=lag($"VALUE",1).over(Window.partitionBy($"ID").orderBy($"TIME")),lit(true)))
  .where($"change")
  //.drop($"change")
  .show()
 

給出:

 +---+----------+----+-----+------+
| ID|      DATE|TIME|VALUE|change|
+---+----------+----+-----+------+
|001|2019-01-01|0010|  150|  true|
|001|2019-01-01|0030|  160|  true|
|001|2019-01-01|0050|  150|  true|
|002|2019-01-01|0010|  151|  true|
|002|2019-01-01|0030|  161|  true|
|002|2019-01-01|0040|  162|  true|
|002|2019-01-01|0051|  152|  true|
+---+----------+----+-----+------+
 

  相同標籤的其他問題

apache-sparkwindow-functions