メインコンテンツまでスキップ

スタック

col1 、...、 colkn行に分割します。特に指定がない限り、デフォルトでは列名 col0、col1 などが使用されます。

構文

Python
from pyspark.sql import functions as sf

sf.stack(*cols)

パラメーター

パラメーター

Type

説明

cols

pyspark.sql.Column または列名

最初の要素は、分離する行数を表すリテラル int である必要があり、残りは分離する入力要素です。

例1 :2行のスタック

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(1, 2, 3)], ['a', 'b', 'c'])
df.select('*', sf.stack(sf.lit(2), df.a, df.b, 'c')).show()
Output
+---+---+---+----+----+
| a| b| c|col0|col1|
+---+---+---+----+----+
| 1| 2| 3| 1| 2|
| 1| 2| 3| 3|NULL|
+---+---+---+----+----+

例2 : エイリアス付きスタック

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(1, 2, 3)], ['a', 'b', 'c'])
df.select('*', sf.stack(sf.lit(2), df.a, df.b, 'c').alias('x', 'y')).show()
Output
+---+---+---+---+----+
| a| b| c| x| y|
+---+---+---+---+----+
| 1| 2| 3| 1| 2|
| 1| 2| 3| 3|NULL|
+---+---+---+---+----+

例3 :3行のスタック

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(1, 2, 3)], ['a', 'b', 'c'])
df.select('*', sf.stack(sf.lit(3), df.a, df.b, 'c')).show()
Output
+---+---+---+----+
| a| b| c|col0|
+---+---+---+----+
| 1| 2| 3| 1|
| 1| 2| 3| 2|
| 1| 2| 3| 3|
+---+---+---+----+

例4 :4行のスタック

Python
from pyspark.sql import functions as sf
df = spark.createDataFrame([(1, 2, 3)], ['a', 'b', 'c'])
df.select('*', sf.stack(sf.lit(4), df.a, df.b, 'c')).show()
Output
+---+---+---+----+
| a| b| c|col0|
+---+---+---+----+
| 1| 2| 3| 1|
| 1| 2| 3| 2|
| 1| 2| 3| 3|
| 1| 2| 3|NULL|
+---+---+---+----+