Freigeben über


Stapel

Trennt col1, ..., colk in n Zeilen. Verwendet Spaltennamen col0, col1 usw. standardmäßig, sofern nicht anders angegeben.

Syntax

from pyspark.sql import functions as sf

sf.stack(*cols)

Die Parameter

Parameter Typ Description
cols pyspark.sql.Column oder Spaltenname Das erste Element sollte ein Literal int sein, damit die Anzahl der zeilen getrennt werden soll, und die restlichen Eingabeelemente sind, die getrennt werden sollen.

Examples

Beispiel 1: Stapel mit 2 Zeilen

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()
+---+---+---+----+----+
|  a|  b|  c|col0|col1|
+---+---+---+----+----+
|  1|  2|  3|   1|   2|
|  1|  2|  3|   3|NULL|
+---+---+---+----+----+

Beispiel 2: Stapel mit Alias

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()
+---+---+---+---+----+
|  a|  b|  c|  x|   y|
+---+---+---+---+----+
|  1|  2|  3|  1|   2|
|  1|  2|  3|  3|NULL|
+---+---+---+---+----+

Beispiel 3: Stapel mit 3 Zeilen

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()
+---+---+---+----+
|  a|  b|  c|col0|
+---+---+---+----+
|  1|  2|  3|   1|
|  1|  2|  3|   2|
|  1|  2|  3|   3|
+---+---+---+----+

Beispiel 4: Stapel mit 4 Zeilen

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()
+---+---+---+----+
|  a|  b|  c|col0|
+---+---+---+----+
|  1|  2|  3|   1|
|  1|  2|  3|   2|
|  1|  2|  3|   3|
|  1|  2|  3|NULL|
+---+---+---+----+