Mol*_*daa 3 scala window-functions apache-spark apache-spark-sql
我有一个数据框架,其中有子类别,并且想要每个这些子类别的最后一个元素。
val windowSpec = Window.partitionBy("name").orderBy("count")
sqlContext
.createDataFrame(
Seq[(String, Int)](
("A", 1),
("A", 2),
("A", 3),
("B", 10),
("B", 20),
("B", 30)
))
.toDF("name", "count")
.withColumn("firstCountOfName", first("count").over(windowSpec))
.withColumn("lastCountOfName", last("count").over(windowSpec))
.show()
Run Code Online (Sandbox Code Playgroud)
给我一些奇怪的东西:
+----+-----+----------------+---------------+
|name|count|firstCountOfName|lastCountOfName|
+----+-----+----------------+---------------+
| B| 10| 10| 10|
| B| 20| 10| 20|
| B| 30| 10| 30|
| A| 1| 1| 1|
| A| 2| 1| 2|
| A| 3| 1| 3|
+----+-----+----------------+---------------+
Run Code Online (Sandbox Code Playgroud)
如我们所见,first返回的值是正确计算的,但last不是,它始终是列的当前值。
是否有人可以解决我想要的事情?
根据问题SPARK-20969,您应该能够通过定义窗口的适当边界来获得预期的结果,如下所示。
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions._
val windowSpec = Window
.partitionBy("name")
.orderBy("count")
.rowsBetween(Window.unboundedPreceding, Window.unboundedFollowing)
sqlContext
.createDataFrame(
Seq[(String, Int)](
("A", 1),
("A", 2),
("A", 3),
("B", 10),
("B", 20),
("B", 30)
))
.toDF("name", "count")
.withColumn("firstCountOfName", first("count").over(windowSpec))
.withColumn("lastCountOfName", last("count").over(windowSpec))
.show()
Run Code Online (Sandbox Code Playgroud)
另外,如果您在计算的第一列和最后一列上都进行排序,则可以更改为非排序窗口,min并max使用一个非排序窗口,则它也应正常工作。
| 归档时间: |
|
| 查看次数: |
2297 次 |
| 最近记录: |