Classe de fenêtre
Fonctions utilitaires pour la définition de fenêtres dans les DataFrames.
Prend en charge Spark Connect
Attributs de classe
Attribut | Description |
|---|---|
| Valeur limite représentant le start d'un cadre de fenêtre illimité. |
| Valeur limite représentant la fin d'un cadre de fenêtre non borné. |
| Valeur limite représentant la ligne actuelle dans un cadre de fenêtre. |
Méthodes
Méthode | Description |
|---|---|
Crée une WindowSpec avec l'ordonnancement défini. | |
Crée un WindowSpec avec le partitionnement défini. | |
Crée un WindowSpec avec les limites de frame définies, de | |
Crée une WindowSpec avec les limites de cadre définies, de |
Notes
Lorsque le classement n'est pas défini, un cadre de fenêtre illimité (rowFrame, unboundedPreceding, unboundedFollowing) est utilisé par default. Lorsque le classement est défini, un cadre de fenêtre croissant (rangeFrame, unboundedPreceding, currentRow) est utilisé par default.
Exemples
Fenêtre de base avec tri et cadre de ligne
from pyspark.sql import Window
# ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
window = Window.orderBy("date").rowsBetween(Window.unboundedPreceding, Window.currentRow)
Fenêtre partitionnée avec un cadre de plage
from pyspark.sql import Window
# PARTITION BY country ORDER BY date RANGE BETWEEN 3 PRECEDING AND 3 FOLLOWING
window = Window.orderBy("date").partitionBy("country").rangeBetween(-3, 3)
Numéro de ligne dans la partition
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"]
)
# Show row number ordered by id within each category partition
window = Window.partitionBy("category").orderBy("id")
df.withColumn("row_number", sf.row_number().over(window)).show()
Somme cumulée avec fenêtre basée sur les lignes
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"]
)
# Sum id values from the current row to the next row within each partition
window = Window.partitionBy("category").orderBy("id").rowsBetween(Window.currentRow, 1)
df.withColumn("sum", sf.sum("id").over(window)).sort("id", "category", "sum").show()
Somme cumulée avec cadre basé sur une plage
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"]
)
# Sum id values from the current id value to id + 1 within each partition
window = Window.partitionBy("category").orderBy("id").rangeBetween(Window.currentRow, 1)
df.withColumn("sum", sf.sum("id").over(window)).sort("id", "category").show()