次の方法で共有


ntile

Window 関数: 順序付けられたウィンドウ パーティション内の ntile グループ ID (1 から n を含む) を返します。 たとえば、 n が 4 の場合、行の最初の四半期は値 1、第 2 四半期は 2、第 3 四半期は 3、最後の四半期は 4 になります。

これは、SQL の NTILE 関数と同じです。

構文

from pyspark.sql import functions as sf

sf.ntile(n)

パラメーター

パラメーター タイプ Description
n 整数 (int) パーティションを分割するグループの数を指定する整数。

返品ポリシー

pyspark.sql.Column: 部分グループ ID。

例示

from pyspark.sql import functions as sf
from pyspark.sql import Window
df = spark.createDataFrame(
    [("a", 1), ("a", 2), ("a", 3), ("b", 8), ("b", 2)], ["c1", "c2"])
df.show()
+---+---+
| c1| c2|
+---+---+
|  a|  1|
|  a|  2|
|  a|  3|
|  b|  8|
|  b|  2|
+---+---+
w = Window.partitionBy("c1").orderBy("c2")
df.withColumn("ntile", sf.ntile(2).over(w)).show()
+---+---+-----+
| c1| c2|ntile|
+---+---+-----+
|  a|  1|    1|
|  a|  2|    1|
|  a|  3|    2|
|  b|  2|    1|
|  b|  8|    2|
+---+---+-----+