rowsBetween (窗口)

使用定义的框架边界创建一个 WindowSpec ,从 start (非独占)到 end (非独占)。

两者都是startend当前行中的相对位置。 例如, 0 表示“当前行”, -1 表示当前行之前的行,表示 5 当前行之后的第五行。

基于行的边界基于分区中行的位置。 偏移量指示帧开始或结束的当前行上方或下方的行数。

Syntax

Window.rowsBetween(start, end)

参数

参数 类型 说明
start int 边界开始(含)。 如果为 Window.unboundedPreceding该帧或小于或等于 -9223372036854775808的任何值,则框架将不受限制。
end int 边界端(含)。 如果为 Window.unboundedFollowing此帧或大于或等于 9223372036854775807的任何值,则框架将不受限制。

退货

WindowSpec

备注

使用 Window.unboundedPrecedingWindow.unboundedFollowing指定 Window.currentRow 特殊边界值,而不是直接使用整型值。

示例

from pyspark.sql import Window, functions as sf

df = spark.createDataFrame(
    [(1, "a"), (1, "a"), (2, "a"), (1, "b"), (2, "b"), (3, "b")], ["id", "category"])

# Calculate the sum of id from the current row to current row + 1 in each category partition.
window = Window.partitionBy("category").orderBy("id").rowsBetween(Window.currentRow, 1)
df.withColumn("sum", sf.sum("id").over(window)).sort("id", "category", "sum").show()
# +---+--------+---+
# | id|category|sum|
# +---+--------+---+
# |  1|       a|  2|
# |  1|       a|  3|
# |  1|       b|  3|
# |  2|       a|  2|
# |  2|       b|  5|
# |  3|       b|  3|
# +---+--------+---+